題目來源於 LeetCode 上第 7號(Reverse Integer)問題,題目難度爲 Easy,AC率25.4%git
題目地址:https://leetcode.com/problems/reverse-integer/面試
Given a 32-bit signed integer, reverse digits of an integer.算法
給定一個32位帶符號整數,反轉整數數組
Example 1:
Input: 123
Output: 321
Example 2:
Input: -123
Output: -321
Example 3:
Input: 120
Output: 21
複製代碼
Note:bash
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.函數
假設只能存儲32位帶符號整數範圍內的整數:[- 2 ^31 , 2 ^31 - 1]。假設函數在反向整數溢出時返回0。post
整數x的取值範圍是:-2 ^31 ~ 2 ^31 - 1(-2147483648~2147483647),假設咱們輸入的整數是1234567899,reverse後就變成了9987654321,超出int最大範圍,也就會出現越界錯誤,因此咱們應該定義一個long型的變量sum來存儲反轉以後的數字ui
經過不斷的取餘運算,從整數的末尾開始,一位一位的移動生成新的數字this
算法效率以下: spa
public int reverse(int x) {
long sum = 0;
while(x != 0){
sum = sum*10 + x%10;
x = x/10;
if(sum > Integer.MAX_VALUE || sum < Integer.MIN_VALUE) return 0;
}
return (int)sum;
}
複製代碼