Palindrome Number(java)
2016-07-04 15:18
405 查看
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.
如果考虑reverse number的方法,可能造成溢出。只能选择分离数字的方法,当然要用到大量除10和取余数的计算。
public class Solution {
public boolean isPalindrome(int x) {
if(x<0){
return false;
}
long reverse=0;
int tmp=x;
while(tmp!=0){
reverse=reverse*10+tmp%10;
tmp/=10;
}
return x==reverse;
}
}
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.
如果考虑reverse number的方法,可能造成溢出。只能选择分离数字的方法,当然要用到大量除10和取余数的计算。
public class Solution {
public boolean isPalindrome(int x) {
if(x<0){
return false;
}
long reverse=0;
int tmp=x;
while(tmp!=0){
reverse=reverse*10+tmp%10;
tmp/=10;
}
return x==reverse;
}
}
相关文章推荐
- Java服务器热部署的实现原理
- java Exception体系结构
- jndi数据源配置
- dubbo启动报错 java.net.UnknownHostException: bogon: bogon: Name or service not known
- javap反编译解释外部类直接使用内部类private字段的原理
- spring在代码中获取bean的方式
- 数据处理---Spring Batch之基础
- 进程上下文与线程上下文
- RXJava的操作符
- 多线程 java文件复制,文件提取,删除,zip压缩工具
- Struts1与Struts2的12点区别
- java入门第一季_1.1_java介绍
- SpringMVC详细示例实战
- struts2的核心和工作原理
- 【基础篇】Eclipse + gitLab + ssh连接
- java中静态代码块的用法 static用法详解
- 几个 Context 上下文的区别
- kafka性能参数和压力测试揭秘
- iReport3.7.1 java打印报表(一)
- 数字证书简介及Java编码实现