Sarim Ahmed
Sarim Ahmed

Reputation: 191

Is there any method in kotlin to get digit at specific index in an "Int"?

I am making a Math quiz and want to perform Addition operation "with carrying". I want to get a digit at specific index but cannot find any method for it. I am currently doing it with convert Int into toString() but some times it doesn't gives correct value. My code:

fun main(args: Array<String>) {
  var a = (100..999).random()
    var b = (1..9).random().toString()    
    var temp = a.toString().get(2)    
    var temp1 = (temp+b)
    var length = temp1.toString().length 

    println(a)
    println(b)
    println("last index: "+temp)
    println("temp1: "+temp1)
    println("length: "+length)

}

Output:

length is greater then 1
a : 771
b : 6
last index : 1
Addition : 16
length : 2

You can see the result. When i add two digits it's doesn't gives the correct value. So is there any method to extract any digit at specific index.

Upvotes: 2

Views: 4525

Answers (3)

Tenfour04
Tenfour04

Reputation: 93581

In your code temp is a Char and b is a String, so the + operator is concatenating them into a new String, not adding numbers. To make this approach work, you would have to convert the Char to a String, and then to an Int:

val a = (100..999).random()
val b = (1..9).random()
val temp = a.toString()[2].toString().toInt()
val temp1 = temp + b
val length = temp1.toString().length

A more straight-forward way to get a digit from a number is to use the remainder operator (aka modulus):

val temp = a % 10

To get digits bigger than the ones place, you have to subtract the result of the next smaller remainder:

val tensPlace = (a % 100 - a % 10) / 10
val hundredsPlace = (a % 1000 - a % 100) / 100

Upvotes: 2

NiciDieNase
NiciDieNase

Reputation: 29

The problem here is, that temp is of type String, so temp+b will do string-concatination instead of mathematical addition.

If you want to do this mathematically, you can:

  1. divide by 10 to the power of digits you want to cut of
  2. cast the result as an integer (effectively cutting of digits after the decimal point)
  3. take that result mod 10 to get the digit you want

So in Kotlin the follwing Code will give you the the forth digit (counting from lowest to highes digit) of your given number.

(1232490 / (10.0).pow(3)).toInt() % 10

Upvotes: -1

ACR
ACR

Reputation: 377

If you are trying to get the last digit of a number, mod operation can help.

771%10 =1
453%10 =3 

Upvotes: 4

Related Questions