LeetCode的第9题Palindrome Number

柔光的暖阳◎ 2022-02-24 12:06 267阅读 0赞

原题如下:

Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.

Example 1:

Input: 121
Output: true
Example 2:

Input: -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
Example 3:

Input: 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
Follow up:

Coud you solve it without converting the integer to a string?

题目翻译:确定整数是否为回文。整数在读取与前向相同的回文时是回文。

原题链接

题目分析:该题容易想到建立数组将输入数据X的每个位进行存储,然后对其进行判断。若x从左边读向右边与从右边读向左边相同,则为回文数。那么负数一定不是回文数(由于负号的存在)。同时0也一定是回文数。在进行判断时需要注意的是在进行存储x的位时,要建立一个计数变量来记录x的位数,方便后面的判断阶段。

AC代码如下:

  1. class Solution
  2. {
  3. public:
  4. bool isPalindrome(int x)
  5. {
  6. if(x<0) return false;
  7. if(x==0) return true;
  8. int a[10]={0};
  9. int yushu=0;
  10. int count=0;//用来记录存储的位数
  11. for(int i=0;i<10;)
  12. {
  13. while(x)
  14. {
  15. yushu=x%10;
  16. a[i]=yushu;
  17. count++;
  18. i++;
  19. x=x/10;
  20. }
  21. break;
  22. }
  23. //进行判断
  24. for(int j=0;j<count;j++)
  25. {
  26. if(a[j]==a[count-1-j]){ }
  27. else return false;
  28. }
  29. return true;
  30. }
  31. };

记得要好好刷题!!

发表评论

表情:
评论列表 (有 0 条评论,267人围观)

还没有评论,来说两句吧...

相关阅读