LeetCode: Reverse Integer
2017-03-12 19:20
302 查看
Reverse Integer
*Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
click to show spoilers.
Note:
The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.
Subscribe to see which companies asked this question.*
解题过程 :
如果输入的是负数,我们先将他化为正数,最后再加上负号,将整数每个位置上的值都按顺序添加到一个数组中,然后用数组将他倒转,要保证倒转后的值不溢出,加一个判断溢出的条件就可以了,代码如下:
*Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
click to show spoilers.
Note:
The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.
Subscribe to see which companies asked this question.*
解题过程 :
如果输入的是负数,我们先将他化为正数,最后再加上负号,将整数每个位置上的值都按顺序添加到一个数组中,然后用数组将他倒转,要保证倒转后的值不溢出,加一个判断溢出的条件就可以了,代码如下:
int reverse(int x) { int s[32]; int i = 0; int flag = 0; if(x<0){ x = -x; flag = 1; } while(x>0){ s[i] = x % 10; x = (x - s[i]) / 10; i++; } long long y = 0; for(int j=0; j<i; j++ ){ y = s[j] * pow(10,i-j-1) + y; } if(y>2147483648 ){ return 0;} if(flag == 0) return y; else return -y; }
相关文章推荐
- 007_LeetCode_7 Reverse Integer 题解
- [Leetcode]Reverse Integer@python
- LeetCode 7 Reverse Integer(翻转整数)
- leetcode:Reverse Integer(一个整数反序输出)
- LeetCode--Reverse Integer(整数反转)Python
- LeetCode 7 Reverse Integer 这道题被血虐
- [Leetcode] reverse integer 反转整数
- LeetCode Reverse Integer
- LeetCode(7)Reverse Integer
- LeetCode 7 : Reverse Integer (Java)
- leetcode Reverse Integer
- leetcode:Reverse digits of an integer
- 【leetcode】整型翻转问题integer reverse
- LeetCode Reverse Integer
- Leetcode在线编程 reverse-integer
- (LeetCode)Reverse Integer --- 反转整数
- leetcode Reverse Integer 2.2 难度系数2
- LEETCODE: Reverse Integer
- Reverse Integer -- leetcode
- Leetcode:Reverse Integer