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

判断一个整数是不是回文整数(例12321)。不能使用多余的空间。

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:

可将此数按位从低到高依次取出,再从高到低反向排列,得到的新数字和原数字比较,一致则是回文数,否则不是。

至于提示中提到反转整数可能会出现int越界的问题,在此题中不会出现。因为如果一个int是回文整数,那么它和自身的反转相等,因此反转后不会越界。如果一个int不是回文数,反转后出现越界的情况,也不会影响结果的判定。

 class Solution {
public:
bool isPalindrome(int x) {
int res = ;
int tmp_x = x; if (x<)
return false; while (tmp_x != ) {
res = res * + tmp_x % ;
tmp_x = tmp_x / ;
} if (res == x) {
return true;
} else {
return false;
} }
};

思路2:

可以将整数中,需要进行比较的首尾数字,不断取出并比较。

 class Solution {
public:
bool isPalindrome(int x) {
if (x < )
return false; int sig = ; while (x / sig >= ) {
sig *= ;
} while (x!=) {
if (x / sig == x % ) {
x = x % sig / ;
sig /= ;
} else {
return false;
}
} return true;
}
};

上面代码在函数中对x进行了修改,为了避免x被修改:

 class Solution {
public:
bool isPalindrome(int x) {
if (x < )
return false; int high = , low = ; while (x / high >= ) {
high *= ;
} while (high > low) {
if (x / high % == x / low % ) {
high /= ;
low *= ;
} else {
return false;
}
} return true;
}
};

附录:

算法中“不使用多余空间”的含义

最新文章

  1. ouath原理
  2. C#读取Excel文件:通过OleDb连接,把excel文件作为数据源来读取
  3. Word Excel 操作总结
  4. 【mysql】利用Navicat for MySQL的使用
  5. 解决Win10服务主机本地系统网络受限
  6. [转]Windows8下设置VS默认启动方式为管理员启动
  7. mysql的ERROR:1042
  8. 如何解决Oracle 11g EM网站报“此网站的安全证书存在问题”
  9. 【Hibernate 9】悲观锁和乐观锁
  10. 8.2.1.3 Range Optimization
  11. iperf网络测试工具
  12. [转]Net Framework引路蜂地图开发示例
  13. git版本控制系统更新
  14. 解决Navicat 出错:1130-host . is not allowed to connect to this MySql server,MySQL
  15. python的配置
  16. UIKit-UIBezierPath
  17. 1657 Distance on Chessboard(简单计算题)
  18. 为PartialView传递一个参数
  19. MongoDB高级操作(2)
  20. SPOJ 8222 NSUBSTR - Substrings

热门文章

  1. Oracle子分区(sub partition)操作
  2. Oracle 常用函数大全
  3. 【网络】访问控制列表(ACL)
  4. java c c++大学补遗
  5. Fastjson解析多级泛型的几种方式&mdash;使用class文件来解析多级泛型
  6. Android 开发手记一NDK编程实例
  7. Android中dip, dp, px,pt, sp之间的区别:
  8. Coursera 机器学习 第5章 Neural Networks: Learning 学习笔记
  9. FZU 1922——非主流——————【技巧题】
  10. js面向对象2