原题地址:
https://leetcode.com/problems/palindrome-number/description/
题目:
Determine whether an integer is a palindrome. Do this without extra space.
解法:
其实就是判断一个数是否回文数。(负数都不是回文数。。。)看到题目就想到是否可以先把它转化为字符串来做,但题目的提示否决了这种方法。同样的,也否决了先把数颠倒过来,比较两数是否相等的做法(有可能溢出)。
我的解法就是先求出这个整数的位数,然后比较第一位和最后一位的数字是否相同,以此类推下来,一直到中间停止。代码如下:
class Solution { public: bool isPalindrome(int x) { if (x < 0) { return false; } int count = 0, copy = x; while (copy) { copy /= 10; count++; } for (int i = 0; i <= (count - 1) / 2; i++) { if ((int)(x / pow(10, i)) % 10 != (int)(x / pow(10, count - i - 1)) % 10) { return false; } } return true; } };
求每一位的数字是多少的那个地方我还想了一下,也就是这两个地方:
(int)(x / pow(10, i)) % 10
(int)(x / pow(10, count - i - 1)) % 10)