Leetcode-reverse-integer
2016-06-26 16:29
435 查看
题目描述
Reverse digits of an integer.Example1: x = 123, return 321
Example2: x = -123, return -321
click to show spoilers.
Have you thought about this?
Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!
If the integer's last digit is 0, what should the output be? ie, cases such as 10, 100.
Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?
Throw an exception? Good, but what if throwing an exception is not an option? You would then have to re-design the function (ie, add an extra parameter).
leetcode上的题目就是各种限制条件多,注意下方的那些提示,有些方法是不能用的。
public class Solution {
public int reverse(int x) {
boolean isfu = false;
if(x == 0)
return 0;
if(x < 0){
x = Math.abs(x);
isfu = true;
}
String str = String.valueOf(x);
char[] charArray = str.toCharArray();
int n = charArray.length;
for(int i=0; i<n/2; i++){
char temp = charArray[i];
charArray[i] = charArray[n-1-i];
charArray[n-1-i] = temp;
}
String res = "";
int j = 0;
for(int i=0; i<n; i++){
if(charArray[i] != '0'){
break;
}
j++;
}
for(int i=j; i<n; i++){
res += charArray[i];
}
int s = Integer.parseInt(res);
if(isfu){
return 0-s;
}else{
return s;
}
}
}首先:是负数的标记出来,并转为正数处理。
其次,倒置处理结束后,寻找到第一个不是0的位置,把该位置后面的所有的数字全部输出出来即可。
最后,如果是负数,则加上符号,不是则输出上述结果。
相关文章推荐
- 4. gpio 库
- Mit os Lab 2. Memory Management
- Python 小练习 倒序切片
- BZOJ 2208: [Jsoi2010]连通数
- 二叉树的遍历。。。
- 面向对象6
- 【阶段总结】这两个月的收获
- 学习 Promise (结合 Rxjava)
- Leetcode-maximum-depth-of-binary-tree
- URL和URI的区别
- postgresql----ANY/SOME&&ALL
- hdu 4525(数学)
- 面试必备
- Android Studio使用gradle-experimental构建NDK工程(无需Android.mk、Application.mk文件)
- strcpy函数的实现
- 【DAY20】Socket编程的补充2
- gitlab工作流程简介
- Qt5以上的建立空Qt项目时
- 求图中最短路径算法之Floyd-Warshall算法——C++实现
- Hadoop源码 YarnRPC通信框架