user5860
user5860

Reputation: 37

Android Studio multiply getting weird result

I'm trying to multiply an array of numbers. Should be pretty simple, but for some reason I'm getting some huge numbers and I can't figure out where I'm doing wrong.

I enter a number, it gets split into an array, it runs through the numbers and multiplis them

        var iArray = i.toString().toCharArray()
        var iCount = iArray.count().toString()
        var x = 0
        var sum: Long = 1

        while(x < iCount.toInt()) {
            Log.i(iArray[x].toString(), "array");
            sum *= iArray[x].toLong()
            x++
            Log.i(sum.toString(), "sum");
        }

In the logcat I can see the correct numbers in the array. As an example, if I try 357 this is what I get as a result

I/3: array I/51: sum

I/5: array I/2703: sum

I/7: array I/148665: sum

But if I just calculate 3*5*7 it works fine. What am I missing?

Upvotes: 2

Views: 199

Answers (1)

touhid udoy
touhid udoy

Reputation: 4442

What your are getting as output, is okay

Because You are multiplying number's ASCII values not the numbers themselves

ASCII values of 3 is 51, 5 is 53, multiplying them results 2703 is right and so on

If you want to use integer multiplication, you have to use convert the character array to an integer array or consider the ASCII values while multiplying.

Ex: sum *= (iArray[x].toLong()-'0') something like this, I dont know kotlin, as you might already noticed. :)

Upvotes: 1

Related Questions