为什么即使 x==sum 这段代码也总是返回 false?

问题描述 投票:0回答:1

公共静态无效主(字符串[]参数) {

    boolean test = test(1221);
    System.out.println(test);
}

 public static boolean test(int x) {
       int d=0, sum=0,count=0;
         while(x>0)
         {
              d=x%10;
              x=x/10;
              sum=sum*10 +d;//3     3*10 + 2    // 32*10 +1
         }
         System.out.println(sum);
        if(x==sum)
        {
             return true;
        }
        
        return false;
     
     }

如果我发送参数 121 ,我应该会得到 true ,对吗?

java palindrome
1个回答
0
投票

X 在 while 循环中发生了变化。该循环直接使用对该值的引用,因此该值在 while 循环之外的范围内发生更改。当到达 if 语句时,x 已减少为 0。您可以通过引入一个取 x 值的临时变量来解决这个问题。例如

public static boolean test(int x) {
    int digit, sum = 0, tempX = x;
    while (tempX > 0) {
        digit = tempX % 10;
        tempX = tempX / 10;
        sum = sum * 10 + digit;//3     3*10 + 2    // 32*10 +1
    }
    System.out.println(sum);
    return x == sum;
}
© www.soinside.com 2019 - 2024. All rights reserved.