Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Long to int conversion in Java gives incorrect result

I am trying seperate out the digits of a long number so that it can be represented as array of integers e.g.

12345......888     as [1,2,3,4,......8,8,8]

In usual way I am taking n%10 to take out last digit and n/10 to reduce the number i.e.

public static void main(String[] args) {
    long temp = 111111111111111110L;
    while(temp>0){
        System.out.println("----------");
        System.out.println(temp%10);
        System.out.println((int)temp%10);
        temp=temp/10;
    }
}

temp%10 gives correct result. But it cannot be directly added to list of int. If I try to type cast it gives incorrect results for first few iterations. Output

----------
0
-2
----------
1
9
----------
1
-5
----------
1
1
----------
1
9
----------
1
-3
----------
1
-5
----------
1
-7
----------
1
1
----------
1
1
----------
1
1
----------
1
1
----------
1
1
----------
1
1
----------
1
1
----------
1
1
----------
1
1
----------
1
1

The workaround I used is

int digitArray[] = new int[somenumber];
String s = Long.toString(n);
for(int i=0;i<s.length();i++){
    digitArray[i]=Integer.parseInt(""+s.charAt(i));
}

But I am curious why type casting is not working in first way when the number being type-casted is single digit i.e. well within range of long.

like image 401
Kaushik Lele Avatar asked Jun 01 '26 12:06

Kaushik Lele


1 Answers

Expression evaluation rules lead to this problem.

when you did

(int)temp%10

Actually the big long value temp being casted to int which leads to integer overflow ,

you meant

(int)(temp%10)
like image 77
Suresh Atta Avatar answered Jun 03 '26 02:06

Suresh Atta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!