[leetcode]7. Reverse Integer反转整数

时间:2022-02-17 13:31:13

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

题意:

给定一个10进制整数,翻转它。

Solution1: directly do the simulation.

Two tricky parts to be handled:

(1) overflow :  32-bit signed integer range: [−231,  231 − 1],  whihc means [−2,147,483,648  2,147,483,647].  What if input is 2,147,483,647, after reversing, it will be 7,463,847,412.

(2) negative numbers: for each iteration, we do multiplication or division with a position number -- 10 , which means if sign is '-' , the sign will be kept all the time.

code:

 /*
Time Complexity: O(log(n)) coz we just travese half part of original input
Space Complexity: O(1)
*/
class Solution {
public int reverse(int input) {
long sum = 0;
while(input !=0){
sum = sum*10 + input %10;
input = input /10; if(sum > Integer.MAX_VALUE || sum < Integer.MIN_VALUE){
return 0; // returns 0 when the reversed integer overflows
}
}
return (int)sum;
}
}