[LeetCode]Palindrome Number
2015-10-08 18:37
197 查看
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.
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.
/* 题号: Determine whether an integer is a palindrome. Do this without extra space. */ #include<iostream> using namespace std; class Solution{ public: bool ispalindrome(int x){ if (x < 0) return false; if (x == 0) return true; int base = 1; while (x / base >= 10) base *= 10; //base为10^n,表示取出数的最高位 while (x){ int leftDigit = x / base; int rightDigit = x % 10; if (leftDigit != rightDigit) return false; x -= base * leftDigit; x /= 10; base /= 100; } return true; } }; int main() { Solution solution; int n1 = -123321; int n2 = 12321; int n3 = 12341; int n4 = 1001; cout << solution.ispalindrome(n1) << endl; cout << solution.ispalindrome(n2) << endl; cout << solution.ispalindrome(n3) << endl; cout << solution.ispalindrome(n4) << endl; getchar(); return 0; }
相关文章推荐
- POJ 2955 Brackets(区间DP水题)
- 10-2总结
- 关于时间
- Java____实现定时任务的三种方法
- ssh配置调试的必杀技
- java多线程基础
- 应用层 加载驱动 和 卸载驱动代码
- The user specified as a definer (''@'') does not exist
- 如何计算时间复杂度
- 【C#高效编程50例】条目2:用运行时常量(readonly)而不是编译期常量(const)
- spring 通过编程来获取属性文件
- 获得URL含有中文出现乱码解决
- 使用VS2013调试Unity
- iOS自适应(代码) 简单介绍一下
- 紧迫感
- eclipse svn操作
- C++中重载、重写(覆盖)和隐藏的区别
- PHP中数字千分位逗号分隔函数number_format()
- Python 实例变量、类变量、静态变量 (十九)
- 【c++ templates读书笔记】【6】模板的多态