有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java正在尝试查找回文数

我试图找到回文“否”,但每次都显示“否”为假,即使是“121” 请帮忙

public boolean isPalindrome(int x) {
        if(x<0 || x%10==0){
            return false;
        }
        int rev = 0;
        while(x!=0){
            rev=(rev*10)+(x%10);
            x/=10;
        }
        
        if(x==rev){
            return true;
        }
        else{
            return false;
        }
    }

enter image description here


共 (5) 个答案

  1. # 1 楼答案

    希望这是有用的:

           public static boolean palindrome(int n) {
                    int nPalindrome = 0;
                    int nCopy = n;
                    while (n != 0) {
                       nPalindrome = nPalindrome *10 + n % 10;
                       n = n / 10;
                }
                if (nCopy == nPalindrom) {
                    return true;
                } else {
                    return false;
                }
        
            }
    
  2. # 2 楼答案

    你的功能可以像下面这样简单

    public static void main(String args[]){  
      int r,sum=0;    
      int n=454;//It is the number variable to be checked for palindrome  
      
      if(isPalindrome(n)) {
       System.out.println("palindrome number ");   
      } else {
       System.out.println("not palindrome number ");   
      }
         
    }  
    
    public boolean isPalindrome(int n)  {
      while(n>0){    
       r=n%10;  //getting remainder  
       sum=(sum*10)+r;    
       n=n/10;    
      }    
    
       return n==sum;    
    }
    
    
  3. # 3 楼答案

    你所需要做的就是在减少原有数量的同时建立新的数量。然后比较两者

    for (int i : new int[]{121,12321, 123,34543,20012}) {
        System.out.printf("%6d - %s%n", i, isPalindrome(i));
    }
        
    public static boolean isPalindrome(int numb) {
        int n = 0;
        for (int b = numb; b > 0;) {
            n *= 10;
            n += b%10;
            b/=10;
        }
        return n == numb;
    }
    

    印刷品

       121 - true
     12321 - true
       123 - false
     34543 - true
     20012 - false
    
  4. # 4 楼答案

    作为一个选项,您可以创建如下内容:

    public boolean isPalindrome(int x) {
        StringBuilder sb = new StringBuilder();
        sb.append(x);
        return sb.toString().equals(sb.reverse().toString());
    }
    
  5. # 5 楼答案

    因为在while循环结束后,x will be 0,您必须对副本执行操作

       public boolean isPalindrome(int x) {
            int num = x;
            if(x<0 || x%10==0){
                return false;
            }
            int rev = 0;
            while(x!=0){
                rev=(rev*10)+(x%10);
                x/=10;
            }
            
            if(num==rev){
                return true;
            }
            else{
                return false;
            }
        }