10000000000%10 在 Java 中返回 8

10000000000%10 returning 8 in Java

Q ) 要反转两个链表,将它们相加 return 和的反转链表 ` 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;
    }
}

对于输入:

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

输出:

num1 = 9 num2 = 9999999991

总和 = 10000000000 l = 8 (这里为什么是10000000000%10=8?)

总和 = 1000000000 l = 0

总和 = 1000000000 l = 0

总和 = 100000000 l = 0

总和 = 10000000 l = 0

总和 = 1000000 l = 0

总和 = 100000 l = 0

总和 = 10000 l = 0

总和=1000 l = 0

总和=100 l = 0

总和 = 10 l = 1

总和=1

请帮忙

int l = (int)sum%10;

问题就在这里。您首先将 long 变量转换为 int 并且然后计算余数。您可能想查看 Storage sizes for primitive datatypes。上面写着以下内容:

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).

换句话说,因为您将大于支持的数字转换为 int,所以您会丢失数据。要解决该问题,请在找到余数后进行转换:

int l = (int)(sum % 10)

或者,更好的是,让你的变量 long.

long l = sum % 10