LeetCode第7题:整数反转 之 先从简单刚起(C++)
2019-01-17 13:46
330 查看
题目描述:
给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。
题目要求:
假设我们的环境只能存储得下 32 位的有符号整数,则其数值范围为 [−231, 231 − 1]。请根据这个假设,如果反转后整数溢出那么就返回 0。
题目示例:
示例 1:输入: 123 输出: 321
示例 2:输入: -123 输出: -321
示例 3:输入: 120 输出: 21
我的想法:
本来考虑是用字符串反转的方法来做,想了一下,感觉需要不停转换类型,太麻烦了。因此,直接对给定的整数下手。
接下来,我想到了十进制转换二进制的思路,对给定数不停的除10取余。这个思路很简单,不值一提。
在测试用例的过程中,主要是给定数反转后会产生溢出的问题。在溢出情况的解决方法上,我是用了一个更大的数据类型long int来存储结果,然后再对结果进行操作。(这个值得稍微提一下hhh)
上代码:
[code]//16ms class Solution { public: int reverse(int x) { int res[32]; int y = x; int i = 0; if(x>(pow(2,31)-1)||x<-pow(2,31)){ return 0; } if(y<0){ y = -y; } while(y!=0){ res[i] = y%10; y = y/10; i++; } long int ans = 0,j = 0; while(i!=0){ ans += res[j]*pow(10,i-1); i--; j++; } if(ans>(pow(2,31)-1)||ans<-pow(2,31)){ ans = 0; } if(x<0){ ans = -ans; } return ans; } };
相关文章推荐
- LeetCode:第7题: 反转整数(reverse-integer)
- Leetcode 整数反转
- 【LeetCode】- Reverse Integer(将一个整数反转)
- LeetCode 7. Reverse Integer 整数反转
- leetcode 7.整数反转
- LeetCode-探索-初级-字符串-整数反转-java
- LeetCode 7. Reverse Integer(反转整数)
- Leetcode:Reverse Integer ,整数反转
- leetcode中文(一) #7反转整数,#77组合
- leetcode 7 使用字符串操作反转整数
- leetcode的python实现 刷题笔记7: 反转整数
- Java&LeetCode 初入门——007. 整数反转
- 反转整数 - LeetCode
- LeetCode--Reverse Integer(整数反转)Python
- (LeetCode)反转整数
- LeetCode7.整数反转 JavaScript
- leetcode之7整数反转
- Leetcode简单题罗马数字转整数
- LeetCode 7 :Reverse Integer ---- 反转int整数
- (LeetCode每日一刷02)反转整数