15算法课程 9. Palindrome Number

来源:互联网 发布:phantomjs java 编辑:程序博客网 时间:2024/06/05 07:32

Determine whether an integer is a palindrome. Do this without extra space.

Some hints:

Could negative integers be palindromes? (ie, -1)

If you are thinking of converting the integer to string, note the restriction of using extra space.

You could also try reversing an integer. However, if you have solved the problem "Reverse Integer", you know that the reversed integer might overflow. How would you handle such case?

There is a more generic way of solving this problem.

solution:

若给定的整数x为负数,直接返回false;否则转2;计算给定整数的位数bit,转3;若给定整数x的位数bit=1,即为一位数,返回ture;否则转4;判断x的第一位与最后一位数是否相同,若相等,转5,若不相等,返回false;x第一位数计算方式为:x整除10的(bit-1)次方,即: x / (int)pow(10,bit-1),如12321,bit=5,第一为:12321/(10^4)=1。x最后一位数计算方式为:x整除10的余数,即:x%10,如12321,最后一位为12321%10=1。除掉x的第一位数和最后一位数,令bit=bit-2,转3;除掉x的第一位数和最后一位数即使12321变为232.计算方法为:x=x%(int)pow(10,bit-1)/10.再令bit=bit-2.

code:

class Solution {  public:      bool isPalindrome(int x) {         if(x<0)//若为负数,返回false              return false;          //计算x为几位数          int bit=1;          while(x/(int)pow(10,bit)!=0)             bit++;            while(bit>1)          {              if((x%10)!=(x/(int)pow(10,bit-1)))//判断第一位数与最后一位数是否相等                  return false;              x=x%(int)pow(10,bit-1)/10;//移除第一位数和最后一位数              bit-=2;          }          return true;      }  }; 



原创粉丝点击