Lunski's Clutter

This is a place to put my clutters, no matter you like it or not, welcome here.

0%

7. Reverse Integer

Given a 32-bit signed integer, reverse digits of an integer.

Note: Assume we are dealing with an environment that could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For this problem, assume that your function returns 0 when the reversed integer overflows.

Example 1:

1
2
Input: x = 123
Output: 321

Example 2:

1
2
Input: x = -123
Output: -321

Example 3:

1
2
Input: x = 120
Output: 21

Example 4:

1
2
Input: x = 0
Output: 0

Constraints:

1
-2ˆ31 <= x <= 231 - 1

Java

x /= 10;

x = 123456789;
x = 12345678;

x % 10;
9
8

reverse = reverse * 10 + x % 10;
987

(int)reverse==reverse?(int)reverse:0;
check integer overflow -2,147,483,647 to 2,147,483,647

1
2
3
4
5
6
7
8
9
10
11
import java.util.*;
class Solution {
public int reverse(int x) {
long reverse = 0;
while(x != 0){
reverse = reverse * 10 + x % 10; // construct reverse integer
x /= 10; // get integer except last
}
return (int)reverse==reverse?(int)reverse:0;
}
}

如果你覺得這篇文章很棒,請你不吝點讚 (゚∀゚)

Welcome to my other publishing channels