`
huntfor
  • 浏览: 194797 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

[leetcode]Reverse Integer

 
阅读更多

这篇博文的代码有bug,新博文地址[leetcode]Reverse Integer

Reverse Integer
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?

Throw an exception? Good, but what if throwing an exception is not an option? You would then have to re-design the function (ie, add an extra parameter).

 两个tips很有意思:

1. 10的倍数,怎么返回?(返回值类型是int,肯定要无视首位的0)

2. 溢出,怎么处理?(这个第一次没考虑到实在是太不应该了)但是就算不处理也AC了,难道是怕每个人处理溢出的做法不同,就没有设置那么强的数据?

不多说,没啥难度,代码如下

 public int reverse(int x) {
		int result = 0;
		while(x!=0){
			int temp = x % 10;
			x /= 10;
			if(10 * result  + temp < Integer.MAX_VALUE || 
			10 * result  + temp > Integer.MIN_VALUE){
				result = 10 * result + temp;
			}else{
				result = 10 * result + temp> Integer.MAX_VALUE?
				Integer.MAX_VALUE:Integer.MIN_VALUE;
			}
		}
		return result;
	
    }

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics