Search code examples
javadata-structureslinked-listmodulo

10000000000%10 returning 8 in Java


Q ) To reverse two linked lists, add them and return a reversed linked list of the sum` https://leetcode.com/problems/add-two-numbers/

class Solution 
{
    public long reverse(long num)
    {
        long ans = 0;
        while(num > 0)
        {
            ans = ans*10 + (num%10);
            num /= 10;
        }
        return ans;
    }
    
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) 
    {
        
        long num1 = 0;
        long num2 = 0;
        while(l1 != null)
        {
            num1 = num1*10 + l1.val;
            l1 = l1.next;
        }
        while(l2 != null)
        {
            num2 = num2*10 + l2.val;
            l2 = l2.next;
        }
        num1 = reverse(num1);
        num2 = reverse(num2);     
        System.out.println("num1 = " + num1);
        System.out.println("num2 = " + num2);
        long sum = num1+num2;
        System.out.println("sum = " + sum);
        int l = (int)sum%10;
        sum /= 10;
        System.out.println("l = " + l);
        System.out.println("sum = " + sum);
        ListNode head = new ListNode(l);
        ListNode l3 = head;
        while(sum > 0)
        {
            l = (int)sum%10;
            System.out.println("l = " + l);
            System.out.println("sum = " + sum);
            sum/=10;
            ListNode temp = new ListNode(l);
            l3.next = temp;
            l3 = l3.next;
        }
        return head;
    }
}

For the input:

[9] [1,9,9,9,9,9,9,9,9,9]

Output:

num1 = 9 num2 = 9999999991

sum = 10000000000 l = 8 (why is 10000000000%10=8 here?)

sum = 1000000000 l = 0

sum = 1000000000 l = 0

sum = 100000000 l = 0

sum = 10000000 l = 0

sum = 1000000 l = 0

sum = 100000 l = 0

sum = 10000 l = 0

sum = 1000 l = 0

sum = 100 l = 0

sum = 10 l = 1

sum = 1

Please help


Solution

  • int l = (int)sum%10;
    

    The problem is here. You are first casting a long variable to int and then calculate the remainder. You might want to check out Storage sizes for primitive datatypes. There it says the following:

    Also known as an integer, int type holds a wide range of non-fractional number values.

    Specifically, Java stores it using 32 bits of memory. In other words, it can represent values from -2,147,483,648 (-231) to 2,147,483,647 (231-1).

    In other words, because you are converting a number larger than supported to int you are getting a loss of data. To fix there problem either cast after finding the remainder:

    int l = (int)(sum % 10)
    

    Or, better yet, just make your variable long.

    long l = sum % 10