标签:style blog http ar io color os sp for
题目 | Reverse Integer |
通过率 | 34.2% |
难度 | Easy |
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
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?
For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
这是一个数字反转的问题,翻转的思想是将原数不断模10取余再除10,从个位按照移位不断得到各个位置的数字,正好是结果从高位到低位的各个位置的数字,对结果的处理正好和原数相反,不断乘10加余数。
此题目需要注意的几点是:
1. 首先对原数x按照几个范围进行划分,a.-10<x<10的范围直接返回x; b.其他情况;
2. 需要设置一个boolean类型变量来标记原数的符号,负数需要转换为正数进行处理,结果再附加上符号;
3. 注意越界的情况,原数不会出现越界,但是反转以后的数字会存在越界的情况!!!!
java代码:
public class Solution { public int reverse(int x) { if(x>-10&&x<10) return x; boolean flag = x>0?true:false; long temp = x; long result =0; temp = temp>0?temp:-temp; while(temp>0) { result = result*10+temp%10; temp /=10; } if(result>Integer.MAX_VALUE){ return 0; }else if(flag) { return (int)result; }else { return -(int)result; } } }
leetcode----------Reverse Integer
标签:style blog http ar io color os sp for
原文地址:http://www.cnblogs.com/pku-min/p/4171452.html