Leetcode刷题(7.整数反转)
2019-06-20 09:34
225 查看
Leetcode刷题(7.整数反转)
一.题目
给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。
示例1:
输入: 123
输出: 321
示例2:
输入: -123
输出: -321
示例3:
输入: 120
输出: 21
注意:
假设我们的环境只能存储得下 32 位的有符号整数,则其数值范围为 [−231, 231 − 1]。请根据这个假设,如果反转后整数溢出那么就返回 0。
二.代码(C)
版本一:
int reverse(int x) { int i,j; double y=0; int temp; int flag=0; if (x==-pow(2,31)) { return 0; } else if (x<0) { x=-x; flag=1; } for (i=1;i<32;i++) { if (pow(10,i)>x &&pow(10,i-1)<=x) { break; } } //printf("%d\n",i); for(j=i;j>0;j--) { temp = x/(int)(pow(10,j-1)); if (temp*pow(10,i-j)>pow(2,31)-1) { return 0; } //printf("temp=%d\n",temp); y=y+temp*pow(10,i-j); //printf("pow=%f\n",pow(10,i-j)); //printf("y=%d\n",y); x = x- temp * (pow(10,j-1)); //printf("x=%d\n",x); } if (flag) { y=-y; } if (y<-pow(2,31) || y>pow(2,31)-1) { return 0; } return y; }
版本二
int pow1(int a,int b) { int y=1; for (;b>0;b--) { y = y*a; } return y; } int reverse(int x) { int i,j; double y=0; int temp; int flag=0; if (x==-pow1(2,31)) { return 0; } else if (x<0) { x=-x; flag=1; } for (i=1;i<32;i++) { //printf("pow1=%d\n",pow1(10,i)); if (pow(10,i)>x &&pow(10,i-1)<=x) { break; } } //printf("%d\n",i); for(j=i;j>0;j--) { temp = x/(int)(pow1(10,j-1)); if (temp*pow(10,i-j)>pow(2,31)-1) { return 0; } //printf("temp=%d\n",temp); y=y+temp*pow1(10,i-j); //printf("pow=%f\n",pow(10,i-j)); //printf("y=%d\n",y); x = x- temp * (pow1(10,j-1)); //printf("x=%d\n",x); } if (flag) { y=-y; } if (y<-pow(2,31) || y>pow(2,31)-1) { return 0; } return y; }
三.提交记录
四.备注
算法本身较简单,主要问题在考虑溢出和正负的判断,代码有很大的进步空间。
相关文章推荐
- LeetCode7.整数反转 JavaScript
- leetcode_7. Reverse Integer 反转整数的各个数字
- LeetCode刷题第一天 第7题整数反转 腾讯50题
- Leetcode题解2:整数反转
- LeetCode刷题笔记 [7] 整数反转
- LeetCode 7. 整数反转
- LeetCode(2)整数反转
- leetcode NO.7 整数反转 腾讯精选练习50
- LeetCode里的7.反转整数问题 Java15行
- 【LeetCode】 #7:反转整数 C语言
- leetcode的python实现 刷题笔记7: 反转整数
- [置顶] [LeetCode] Reverse Integer 整数反转
- C语言刷LeetCode:简单篇:整数反转
- leetcode 007 反转整数
- 【菜鸡的LeetCode答案】【C#】7.反转整数
- LeetCode-7-反转整数-c# 版本
- LeetCode--7.整数反转(Reverse Integer)
- LeetCode给出一个 32 位的有符号整数,将这个整数中每位上的数字进行反转。
- LeetCode 7 反转整数
- [leetcode 7] Reverse Integer(整数反转) c函数实现