• Reverse Integer


    原题链接https://leetcode.com/problems/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?

    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.

    原本是有buge(不考虑溢出)也能通过的,可是如今不行了。须要考虑溢出问题

    以下是我用Java写的,AC通过。

    。(当中推断溢出的部分參考了他人代码。链接在此:http://blog.csdn.net/stephen_wong/article/details/28779481

    public class Solution {
        public int reverse(int x) {
            int res = 0;
            int flag = 0;
            
            if(checkOverflow(x)) {
                return 0;
            } else {
            
                if(x < 0) {
                    flag = 1;
                    x = -x;
                }
                
                while(x>0) {
                    res = x % 10 + res * 10;
                    x /= 10;
                }
                
                if(flag == 1) {
                    return -res;
                }
                return res;
            }
        }
        
        public static boolean checkOverflow(int x) {
    		if(x/1000000000 == 0) {  //x的绝对值小于1000000000。不越界
    			return false;
    		} else if(x == Integer.MIN_VALUE) {//Integer.MIN_VALUE = -2147483648。反转后越界,也没法按下述方法取绝对值(以下绝对值的方法相当于对排除了正、负数的影响)
    			return true;
    		}
    		
    		x = Math.abs(x);
    		 // x = d463847412 ->  2147483647. (參数x,本身没有越界,所以d肯定是1或2)   
    		 // or -d463847412 -> -2147483648. 
    		for(int cmp = 463847412; cmp != 0; cmp/=10,x/=10) {
    			if(x%10 > cmp%10) {
    				return true;
    			} else if(x%10<cmp%10) { //x从个位(低位)到高位依次与整型上界从高位到地位比較。x的每一位必须小于整型上界的每一位才不会越界,否则越界
    				return false;
    			}
    		}
    		return false;
    	}
        
    }


     

  • 相关阅读:
    js控制表格隔行变色
    浅谈css的伪元素::after和::before
    CSS 背景色变化 结构化伪类的练习
    css清除浮动的几种方式,哪种最合适?
    怎么去检测浏览器支不支持html5和css3?
    display:flex 布局详解(2)
    css3弹性盒子display:flex
    Referer和空Referer
    不要懒惰,坚持每周总结一篇博客
    比较2个文件的不同处
  • 原文地址:https://www.cnblogs.com/yxysuanfa/p/7190248.html
Copyright © 2020-2023  润新知