Reverse binary representation of the integer
Given an unsigned Integer, reverse the bits of binary representation of the Integer
Unsigned Integer 10
14 -> 1110
reverse 1110 -> 0111
0 1 1 1 is 1 + 2 + 4 = 7
Reverse Bits of Unsigned Integer in Java
1. Convert an integer to binary representation
2. Convert a binary representation to decimal in reverse order
# Convert Integer to binary
public static List toBinary(Integer n){
List ls = new ArrayList<>();
if(n == 0){
ls.add(0);
}else{
while(n > 0){
Integer r = n % 2;
Integer q = n / 2;
ls.add(r);
n = q;
}
}
return ls;
}
Collections.reverse(ls);
// binary to decimal
int s = 0;
for(int i = 0; i < ls.size(); i++){
Integer p = Math.pow(10, i);
s += ls.get(i) * p;
}
pl("s=" + s);
Related question
Find the GCD of two integers
gcd(a, b) = gcd(a - b, b) where a >= b)
gcd ← {⍺ = 0 : ⍵ ⋄ ⍵ = 0 : ⍺ ⋄ ⍺ > ⍵ : (⍺ - ⍵) ∇ ⍵ ⋄ ⍺ ∇ ⍵ - ⍺}
int gcd(int a, int b){
if( a == 0){
return b;
} if (b == 0){
return a;
}else{
return a >= b ? gcd(a - b, b) : gcd(a, b - a);
}
}
gcd(0, b) = b
gcd(a, 0) = a
gcd(0, 0) = undefined
Find the GCD of a list of integers
List ls = new ArrayList<>();
ls.addAll(10, 20, 12, 8);
// smart way to take the advantage of gcd(0, a) => a
int g = 0;
for(int i = 0; i < ls.size(); i++){
g = gcd(g, ls.get(i));
}