Write a program that reads a three-digit number(923), reverses the order of its digits, and outputs a new number(329) in Kotlin? - kotlin

import java.util.Scanner
fun main() {
val scanner = Scanner(System.in)
}
I know there is possibility of using String.reversed() but the exercise is part of Integers in action so I need to solve it only with integers.

thats pretty easy,
var num = 923
var reversed = 0
while (num != 0) {
val digit = num % 10
reversed = reversed * 10 + digit
num /= 10
}
println("Reversed Number: $reversed")

Related

print n times number from 1. Need print (1 2 2 3 3 3 4)

I can't figure out how to solve the following problem: there is a number n. Output the numbers to the console in order separated by a space, but so that the next digit in the iteration is output as many times as it is a digit, and at the same time so that there are no more than n digits in the output. Сan anyone suggest the correct algorithm?
example: have n = 7, need print (1 2 2 3 3 3 4) in kotlin
what i try:
var n = 7
var count = 1
var i = 1
for (count in 1..n) {
for (i in 1..count) {
print(count)
}
}
}
var n = 11
var count = 1
var i = 1
var size = 0
// loop# for naming a loop in kotlin and inside another loop we can break or continue from outer loop
loop# for (count in 1..n) {
for (i in 1..count) {
print(count)
size++
if (size == n){
break#loop
}
}
}
You can use "#" for naming loops and if you want to break from that loop, you can use this syntax in kotlin. It worked for me.
For kotlin labeled break you can look at this reference: link
var count = 1
var n = 7
for(count in 1..n) {
print(count.toString().repeat(count))
}
count.toString() converts an integer to a string, .repeat() function repeats count times the string.
In case you need to add a space between each number, you can add the following:
print(" ")
Using generateSequence and Collections functions:
val n = 7
println(generateSequence(1) {it + 1}
.flatMap{e -> List(e){e}}
.take(n)
.joinToString(" "))
Your example is correct, You have to put a space between the printing
you can follow the code from this link
Kotlin lang code snippet
or the following code snippet
fun main() {
var n = 7
var count = 1
var i = 1
for (count in 1..n) {
for (i in 1..count) {
print(count)
print(' ')
}
}
}
For completeness, here's another approach where you write your own sequence function which produces individual values on demand (instead of creating intermediate lists)
sequence {
var digit = 1
while (true) {
for (i in 1..digit) yield(digit)
digit++
}
}.take(7)
.joinToString(" ")
.run(::print)
Not a big deal in this situation, but good to know!

Write a kotlin program that prints the number that is repeated the most in a consecutive way

I'm kind of stuck, I don't know how to make the second loop to start 1 position above the first loop in Kotlin.
I have an array (named myArray) with 10 elements, I need to Write a Kotlin program that prints the number that has the most consecutive repeated number in the array and also prints the number of times it appears in the sequence.
The program must parse the array from left to right so that if two numbers meet the condition, the one that appears first from left to right will be printed.
Longest: 3
Number: 8
fun main() {
val myArray: IntArray = intArrayOf(1,2,2,4,5,6,7,8,8,8)
for((index , value) in myArray.withIndex()){
var inx = index + 1
var count = 0
var longest = 0
var number = 0
for((inx,element) in myArray.withIndex()) {
if(value == element ){
count+=
}
}
if(longest < count){
longest = count
number = value
}
}
}
I'm against just dropping answers, but it is quite late for me, so I'll leave this answer here and edit it tomorrow with more info on how each part works. I hope that maybe in the meanwhile it will help you to gain some idea to where you might be going wrong.
val results = mutableMapOf<Int, Int>()
(0..myArray.size - 2).forEach { index ->
val current = myArray[index]
if (current == myArray[index + 1]) {
results[current] = (results[current] ?: 1) + 1
}
}
val (max, occurrences) = results.maxByOrNull { it.value } ?: run { println("No multiple occurrences"); return }
println("Most common consecutive number $max, with $occurrences occurrences")
Alternatively if the intArray would be a list, or if we allowed to change it to a list myArray.toList(), you could replace the whole forEach loop with a zipWithNext. But I'm pretty sure that this is a HW question, so I doubt this is the expected way of solving it.
myList.zipWithNext { a, b ->
if (a == b) results[a] = (results[a] ?: 1) + 1
}

My kotlin code gives the wrong answer for the largest and smallest values in a list and I don't know why

This was a simple code wars question but my code gives the wrong answer for the largest value and smallest value. I have checked every section but I can't seem to make it work. I have looked at the solutions for this problem but I wanted to find out what I was doing wrong in the first place.
fun highAndLow(numbers: String): String {
val splitNum = numbers.split(" ")
var largestNum = splitNum[0]
var smallestNum = splitNum[0]
for (num in splitNum) {
if (largestNum < num) {
largestNum = num
}
if (num < smallestNum) {
smallestNum = num
}
}
return "$largestNum $smallestNum"
}
fun main() {
print(highAndLow("8 3 -5 42 -1 0 0 -9 4 7 4 -4 9"))
}
Expected output: 42 -9
Current output: 9 -1
You are comparing strings, not integers. Use toInt() to convert a string into an integer.
val splitNum = numbers.split(" ").map { it.toInt() }
A little tip by the way: perhaps the code could be optimised even further. Have a look here:
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/min-by-or-null.html
and
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/max-by-or-null.html

scanner in kotlin to read in 2 lines

Here is the code. n continually outputs 50 and not 2:
import java.util.*
fun main(args: Array<String>) {
val scanner = Scanner(System.`in`)
val n = scanner.next().first().toInt()
val array1 = readLine()!!.split(" ").map { it.toInt() }
var product:Int=0
println(n)
println(array1[0])
println(array1[1])
if (n ==2) {
product = array1[0] * array1[1]
}
println(product)
}
Sample Input:
2
5 3
Output:
2
5 3
50
5
3
0
How do I use scanner in kotlin to read in 2 lines?
Short form
Use scanner.nextInt() instead of scanner.next().first().toInt().
Explanation
By calling scanner.next() you receive the next complete token of the Scanner as a String. Then you take the first character using first(). The problem is, that calling toInt() on a Char will not parse the string as an integer value but return the ASCII char code of the char.
Example: '2'.toInt() returns 50 and not 2 since the ASCII char code of 2 is 50. (See https://www.cs.cmu.edu/~pattis/15-1XX/common/handouts/ascii.html)
Conclusion: In your case, directly read the integer value from the Scanner using scanner.nextInt(), but if you want to convert a char to an integer by "parsing", convert it to a string first: '2'.toString().toInt() will return an integer with the value 2
Addition
It is probably nice to know that you can also use this the other way round: 50.toChar() returns a character with the value '2'.
👍

Can an integer in Kotlin be equal to an math expression?

I am making a program that solves a math expression, for example, 2+2. Can I set an integer equal to something like this:
val input = "2+2"
input.toInt()
Kotlin doesn't have any built in ways for evaluating arbitrary expressions. The toInt function can only parse a String containing a single whole number (it's just a wrapper for Integer.parseInt).
If you need this functionality, you'll have to parse and evaluate the expression yourself. This problem is no different than having to do it in Java, for which you can find discussion and multiple solutions (including hacks, code samples, and libraries) here.
No you cannot convert directly a String Mathematical Expression to Integer.
But you can try following approach to convert String Mathematical Expression to Integer ->>
var exp: String = "2+3-1*6/4"
var num: String = ""
var symbol: Char = '+'
var result: Int = 0
for(i in exp)
{
if(i in '0'..'9')
num += i
else
{
if(symbol == '+')
result += Integer.parseInt(num)
else if(symbol == '-')
result -= Integer.parseInt(num)
else if(symbol == '*')
result *= Integer.parseInt(num)
else if(symbol == '/')
result /= Integer.parseInt(num)
num=""
symbol = i
}
}
//To calculate the divide by 4 ( result/4 ) in this case
if(symbol == '+')
result += Integer.parseInt(num)
else if(symbol == '-')
result -= Integer.parseInt(num)
else if(symbol == '*')
result *= Integer.parseInt(num)
else if(symbol == '/')
result /= Integer.parseInt(num)
println("result is $result") //Output=> result is 6
}
No you can't.
You can like this:
val a = "2"
val b = "2"
val c = a.toInt() + b.toInt()
Or
val input = "2+2"
val s = input.split("+")
val result = s[0].toInt() + s[1].toInt()
This can be done with the kotlin script engine. For details see Dynamically evaluating templated Strings in Kotlin
But in a nutshell it's like this:
val engine = ScriptEngineManager().getEngineByExtension("kts")!!
engine.eval("val x = 3")
val res = engine.eval("x + 2")
Assert.assertEquals(5, res)
No, Integer cannot be equal to math expression.
You may use String Templates
Strings may contain template expressions, i.e. pieces of code that are evaluated and whose results are concatenated into the
string.
A template expression starts with a dollar sign ($) and consists of either a simple name:
val i = 10
val s = "i = $i" // evaluates to "i = 10"