Chinaunix首页 | 论坛 | 博客
  • 博客访问: 119572
  • 博文数量: 53
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 620
  • 用 户 组: 普通用户
  • 注册时间: 2014-08-24 16:22
文章存档

2014年(53)

我的朋友

分类: C/C++

2014-09-18 10:06:09

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.

就是获得一个整数的各个位的值,以及求整数的长度,负数直接排除。

  1. bool isPalindrome(int x) {
  2.         if(x<0)
  3.             return false;
  4.         int t=x;
  5.         int length=0;
  6.         while(t){
  7.             t=t/10;
  8.             length++;
  9.         }
  10.         for(int i=0;i<length/2;i++){
  11.             if(f(x,i)!=f(x,length-1-i))
  12.                 return false;
  13.         }
  14.         return true;
  15.     }
  16.     int f(int x, int n){
  17.         for(int i=0;i<n;i++){
  18.             x=x/10;
  19.         }
  20.         return x%10;
  21.     }


阅读(726) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~