Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
Example1: x = 123, return 321
Example2: x = -123, return -321
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.
public int reverseBits(int n) {
int res = 0;
for(int i = 0; i < 32; i++, n >>= 1){
res = res << 1 | (n & 1);
}
return res;
}
public int reverseBits(int n) {
int result = 0;
for (int i = 0; i < 32; i++) {
result += n & 1;
n >>>= 1; // CATCH: must do unsigned shift
if (i < 31) // CATCH: for last digit, don't shift!
result <<= 1;
}
return result;
}
How to optimize if this function is called multiple times? We can divide an int into 4 bytes, and reverse each byte then combine into an int. For each byte, we can use cache to improve performance.
private final Map<Byte, Integer> cache = new HashMap<Byte, Integer>();
public int reverseBits(int n) {
byte[] bytes = new byte[4];
for (int i = 0; i < 4; i++) // convert int into 4 bytes
bytes[i] = (byte)((n >>> 8*i) & 0xFF);
int result = 0;
for (int i = 0; i < 4; i++) {
result += reverseByte(bytes[i]); // reverse per byte
if (i < 3)
result <<= 8;
}
return result;
}
private int reverseByte(byte b) {
Integer value = cache.get(b); // first look up from cache
if (value != null)
return value;
value = 0;
// reverse by bit
for (int i = 0; i < 8; i++) {
value += ((b >>> i) & 1);
if (i < 7)
value <<= 1;
}
cache.put(b, value);
return value;
}
What questions would you ask? Here are mine:
- Can it be negative?
- Of course. Example 2: x = -123, return -321.
(Well, it turns out we don't need to explicitly address the sign in the solution unless you want to use a string. Mod, %, will preserve the sign of the input number.) - What if it is ended with 0's?
- The output should be a valid number. That said, if x = 100, return 1. - What if reversed numer is greater than Integer.MAX_VALUE?
- What will you do to handle it?
- Throw an overflow exception or in C++, change the method signature to be something likebool reverse(int x, int res);
int reverse( int x) { int result = 0; while (x != 0){ result = result * 10 + x % 10; x = x / 10; } return result; } |
public int reverse(int x) { //flag marks if x is negative boolean flag = false; if (x < 0) { x = 0 - x; flag = true; } int res = 0; int p = x; while (p > 0) { int mod = p % 10; p = p / 10; res = res * 10 + mod; } if (flag) { res = 0 - res; } return res; } |
https://leetcode.com/discuss/120/how-do-we-handle-the-overflow-case
https://leetcode.com/discuss/25502/simple-java-solution-o-n-time-and-o-1-space
Simply just modulo the input by 10, add it to a long-integer variable as the result. Repeat. When the result is > max integer or < min integer, return 0. Hence, return the result as an integer
Use bigger data type to detect overflow.public int reverse(int x) { long rev= 0;//\\ while( x != 0){ rev= rev*10 + x % 10; x= x/10; if( rev > Integer.MAX_VALUE || rev < Integer.MIN_VALUE) return 0; } return (int) rev; }
https://leetcode.com/discuss/77499/5-lines-2ms-java-solution
public int reverse(int x) { long answer = 0; while(x != 0) { answer = 10 * answer + x % 10; x /= 10; } return (answer > Integer.MAX_VALUE || answer < Integer.MIN_VALUE) ? 0 : (int) answer; }
关于Integer越界的处理
这里的res就是以上两题中, 每次需要做 res = res*10 + update_value的结果值, 我们在更新res前判断下次更新会不会越界(超过Integer.MAX_VALUE).
http://www.geeksforgeeks.org/write-a-c-program-to-reverse-digits-of-a-number/
int
reversDigits(
int
num)
{
static
int
rev_num = 0;
static
int
base_pos = 1;
if
(num > 0)
{
reversDigits(num/10);
rev_num += (num%10)*base_pos;
base_pos *= 10;
}
return
rev_num;
Java code from http://stackoverflow.com/questions/16392459/recursion-digits-in-reverse-order
public static void reversDigits(long number) {
if (number < 10) {
System.out.println(number);
return;
}
else {
System.out.println(number % 10);
reversDigits(number/10);
}
}
Consider Overflow:http://www.shuatiblog.com/blog/2014/04/28/reverse-integer/
First, using long type to avoid overflow.
Second, do boundary check in every step.
https://github.com/haoel/leetcode/blob/master/algorithms/reverseInteger/reverseInteger.cpp
#define INT_MAX 2147483647
#define INT_MIN (-INT_MAX - 1)
int reverse(int x) {
int y=0;
int n;
while( x != 0){
n = x%10;
//Checking the over/underflow.
//Actually, it should be y>(INT_MAX-n)/10, but n/10 is 0, so omit it.
if ((y -n) > INT_MAX/10 || y < INT_MIN/10){
return 0;
}
y = y*10 + n;
x /= 10;
}
return y;
}
http://www.zhuangjingyang.com/leetcode-reverse-integer/
public static int reverse(int x) {
String isNegative = "";
if(x<0){
x = -x;
isNegative = "-";
}
//cover to stringBuffer
String temp = "" + x;
StringBuffer rev = new StringBuffer(temp);
rev = rev.reverse();
String max = "" + Integer.MAX_VALUE;
if(rev.toString().length()>max.length() || (rev.toString().length() == max.length() && rev.toString().compareTo(max) >0 ))
return 0;
return Integer.parseInt(isNegative + rev.toString());
}
Reverse bits of an unsigned integer.There is a constant solution for reversing 4-byte-long binary by using bit manipulations.
The basic idea is to use Divide and Conquer algorithm.
- Switch the neighboring bits, i.e. 1001 -> 0110
- Switch the neighboring two bits, i.e. 1011 -> 1110
- ...
- Switch the neighboring two bytes.
unsigned int reverseBinary(unsigned int x) {
x = ((x & 0x55555555) << 1) | ((x & 0xAAAAAAAA) >> 1);
x = ((x & 0x33333333) << 2) | ((x & 0xCCCCCCCC) >> 2);
x = ((x & 0x0F0F0F0F) << 4) | ((x & 0xF0F0F0F0) >> 4);
x = ((x & 0x00FF00FF) << 8) | ((x & 0xFF00FF00) >> 8);
x = ((x & 0x0000FFFF) << 16) | ((x & 0xFFFF0000) >> 16);
return x;
}
Read full article from Reverse Integer leetcode | easycpp