leetcode第7題——*Reverse Integer

題目

Reverse digits of an integer.

Example1: x = 123, return 321
Example2: x = -123, return -321

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.

思路

先將各位上的數字分別取出依次存放在一個數組裏(個位、十位、百位、千位...),然後倒序取出數組即可(...、千位、百位、十位、個位),將結果存在res變量中,for循環得到res變量的值:res += a[i]*10^x。這裏要注意的是翻轉後溢出的情況——如果用Python編寫,由於Python裏不用聲明變量類型,就算結果大於0x7fffffff也會自動轉爲長整型,因此直接用|res|>0x7fffffff表示溢出的情況;如果用Java編寫,事先聲明瞭int型變量,結果大於0x7fffffff則只會截取低32位的數,因此可以用最高位來判斷是否溢出,詳細設計見代碼部分。

代碼

Python

class Solution(object):
    def reverse(self, x):
        """
        :type x: int
        :rtype: int
        """
        x_abs = abs(x)
        if (x_abs == 2147483648):
            return 0
        if (x_abs < 10):
            return x
        base = 1
        res,i = 0,0
        arr = []
        while (x_abs/(base*10) > 0) & (i < 10):
            base = pow(10,i)
            arr.append((x_abs/base)%10)
            i += 1
        i -= 1
        for j in range(i,-1,-1):
            if (arr[j] != 0):
                base = pow(10,abs(j-i))
                res += arr[j]*base#例如三位數123,原來的個位變百位,百位變個位
                if (res < 2147483648):
                    continue
                else:
                    return 0#溢出處理
        if (x < 0):
            return -res
        else:
            return res

Java

public class Solution {
    public int reverse(int x) {
        int x_abs = Math.abs(x);
		//特殊情況的處理
		if(x == -2147483648) return 0;
		if (x_abs < 10) return x;
		
		int[] arr = new int[11];
		int base = 1;
		int i,j;
		int res = 0;
	
		for(i = 0;x_abs/(base*10) > 0 && i < 10;i++){
			//將個位、十位、百位的數依次存在數組裏
			base = (int)Math.pow(10, i);
			arr[i] = (x_abs/base)%10;
		}

		i -= 1;
		for(j = i;j >= 0;j--){
			if(arr[j] != 0){
					//例如三位數123,原來的個位變百位,百位變個位
					base = (int)Math.pow(10, Math.abs(j - i));
					res += arr[j]*base;
					//如果相加後的最高位是a[j]繼續下次循環,否則代表溢出
					if(res/base == arr[j]) continue;
					else return 0;
			}
		}
		if(x < 0)
			return -res;
		else
			return res;
    }
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章