繁体   English   中英

"负回文数失败"

[英]negative palindrome number failure

我需要确定一个数字是否是回文例如:121 是,例如:-121 不是。 该程序似乎适用于回文数,但是我无法找出负数和非回文数

class Solution {
public:
    bool isPalindrome(int x) {
        int reverse = 0;
        int digit;
        int n = x;
        bool t = true;
         while(x > 0){
             digit = x%10;
             reverse = (reverse*10) + digit;
             x = x/10;  
         }
        if (n == reverse) {
         return t;
        } 
        else if(n != reverse) {
            return -1;
        }
    return -1;
         
    }
};
bool isPalindrome(int A)
{
int Rev{ 0 } , rem , C{ A };

while( ( abs( A ) ) ! = 0 )
{
rem = ( abs( A ) ) % 10;
Rev = Rev * 10 + rem;
A / = 10;
}

if( C ! = Rev or C < 0)
 return false;

else if( C == Rev and C > 0)
 return true;
}

使用以下内容更改您的 if 语句,然后这适用于负数。

希望这对你有用!!

class Solution {
  public boolean isPalindrome(int x){
    int reverse=0;
  int duplicate_x=x;
    for(int i=0;i<=x;i++)
       {
      int r=x%10;
      reverse=(reverse*10)+r;
      x=x/10;
        }
        if(x>=1){       **wrote this if condition to catch  unit place number**
         reverse=(reverse*10)+x;
        }
         if(reverse==duplicate_x)
            {
              return true;
             }
            else
            {
           return false; 
            }
          }
}

我使用 for 循环是因为我在 leetcode 中的时间超过了错误,并且您在关于负数回文的问题中提到过我不明白为什么我们要为那些我们知道 ** 负数不能为负数的回文编写代码一个回文数! 如果我错了,请纠正我

int x=121;
    if(x<0){
        System.out.println("false");
        System.exit(0); 
    }
    int div, sum=0;
    int res=x;
    while(x!=0){
        div = x%10;
        sum = sum*10 + div;
        x=x/10;
    }
    if(sum==res)
        System.out.println("True");

无法想出比这个更简单的解决方案。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM