LeetCode:整數反轉
Problem Description
整數反轉
給出一個 32 位的有符號整數,你需要將這個整數中每位上的數字進行反轉。
示例 1:
輸入: 123 輸出: 321
示例 2:
輸入: -123 輸出: -321
示例 3:
輸入: 120 輸出: 21
注意:
假設我們的環境只能儲存得下 32 位的有符號整數,則其數值範圍為 [−2^31, 2^31 − 1]。請根據這個假設,如果反轉後整數溢位那麼就返回 0。
Reverse Integer
Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123 Output: 321
Example 2:
Input: -123 Output: -321
Example 3:
Input: 120 Output: 21
Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−2^31, 2^31 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
Solution
思路
我們可以一次構建反轉整數的一位數字。在這樣做的時候,我們可以預先檢查向原整數附加另一位數字是否會導致溢位。
演算法
反轉整數的方法可以與反轉字串進行類比。
我們想重複“彈出” x 的最後一位數字,並將它“推入”到 rev 的後面。最後,rev 將與 x 相反。
要在沒有輔助堆疊 / 陣列的幫助下 “彈出” 和 “推入” 數字,我們可以使用數學方法。
//彈出操作 pop = x % 10; x /= 10; //推入操作 temp = rev * 10 + pop; rev = temp;
但是,這種方法很危險,因為當 temp = rev ⋅ 10 + pop 時會導致溢位。
public class Solution { /** * Integer.MAX_VALUE = 0x7fffffff = 2^31-1 = 2147483647 * Integer.MIN_VALUE = 0x80000000 = -2^31 = -2147483648 */ public int reverse(int x) { int result = 0; while(x != 0) { int pop = x % 10; int rev = result * 10 + pop; if ((rev - pop) / 10 != result) { return 0; } result = rev; x = x / 10; } return result; } }
複雜度分析
-
時間複雜度:O(log(x)),x 中大約有 log10(x) 位數字。
-
空間複雜度:O(1)。
Reference
https://leetcode-cn.com/problems/reverse-integer/
https://leetcode.com/problems/reverse-integer/