简体   繁体   English

"负回文数失败"

[英]negative palindrome number failure

i need to determine if a number is palindrome or not ex: 121 yes, ex: -121 no.我需要确定一个数字是否是回文例如:121 是,例如:-121 不是。 the program seems to work with palindrome numbers however i am having trouble figuring out the negative numbers, and non palindrome numbers该程序似乎适用于回文数,但是我无法找出负数和非回文数

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;
}

Change your if statements with the following and then this works for negative numbers.使用以下内容更改您的 if 语句,然后这适用于负数。

Hope this works for you!!希望这对你有用!!

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; 
            }
          }
}

I used for loop because I was getting time exceeding error in leetcode and has you mention in your question about negative number palindrome I don't get it why should we write code for those negative number palindrome where we know a **negative number cannot be a palindrome number!我使用 for 循环是因为我在 leetcode 中的时间超过了错误,并且您在关于负数回文的问题中提到过我不明白为什么我们要为那些我们知道 ** 负数不能为负数的回文编写代码一个回文数! Please correct me if I am wrong如果我错了,请纠正我

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");

Can't be able to come up with a simple solution more than this one.无法想出比这个更简单的解决方案。

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

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