LEETCODE-Reverse Integer
2015-10-18 13:26
323 查看
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?
For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
Update (2014-11-10):
Test cases had been added to test the overflow behavior.
没想出什么好的方法来解决反转后的数据溢出;
通过写了一个Yesorno()判断函数;
就采用将x反转后得到i的y再反转得到z;
判断x与z是否相等;若不相等则判定为发生溢出,return 0;相等则返回y的值;
中心反转算法:
思想与Reverse Bits这一题差不多反转的过程都是:
将原数的最后一位给到新数;
然后原数去除最后一位;
新数将得到的位依次向后排列;
最后原数一位也没有了;
而新数也反转完毕了;
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?
For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
Update (2014-11-10):
Test cases had been added to test the overflow behavior.
没想出什么好的方法来解决反转后的数据溢出;
通过写了一个Yesorno()判断函数;
就采用将x反转后得到i的y再反转得到z;
判断x与z是否相等;若不相等则判定为发生溢出,return 0;相等则返回y的值;
class Solution { public: bool Yesorno(int y, int x){ int z = 0; while(y){ z = z * 10 + y % 10; y /= 10; } if(z == x) return 1; else return 0; } int reverse(int x) { int y = 0; // 如果此处不判断是否为零,如x为0则在下面的while陷入死循环;->(如下:) if( x == 0 ) return 0; //去掉x末尾的0,避免在Yesorno进行比较时发生错误;例如:x=10 -> y=1 ->z=1(y再进行反转得到的不是10,而是1);->(如下 :) while( x%10 == 0) x /= 10; int X = x; while(x){ y = y * 10 + 4000 x % 10; x /=10; } int Y = y; if(Yesorno( Y, X)) return y; else return 0; } };
中心反转算法:
int y = 0; while(x){ y = y * 10 + x % 10; x /=10; }
思想与Reverse Bits这一题差不多反转的过程都是:
将原数的最后一位给到新数;
然后原数去除最后一位;
新数将得到的位依次向后排列;
最后原数一位也没有了;
而新数也反转完毕了;
相关文章推荐
- 关于android屏幕分辨率适配的知识的整理
- CSDN-markdown编辑器手册
- 利用split方法 分割又都好的字符串成数组
- java中的8个基本数据类型
- iOS开发- 隐藏键盘总结
- 学习第一周期
- DataSet和DataTable详解
- 待解决的问题——缺少插件
- 百度基础技术测试部一面2015/10/15 实习生
- 简单介绍数据流动的控制
- hdu 3333 线段树离线操作
- (158)两个字符串是变位词
- 第一行代码笔记10(WebView控件)
- asp.net的自定义控件和用户控件的区别
- 程序员的境界升华
- 一、Linux下MySQL安装和卸载图文教程详解
- iptables命令
- 读《UML大战需求分析》有感一
- DDD事件总线的实现
- 如何使用在三星840 SSD硬件加密下使用Bitlocker