I am trying to check if a number (input as a String
) is a power of 2. The problem is that the number might be greater than 2^64
(long long limit). If I store it in double
then I cannot do binary operations on it (so the trick v & (v - 1) == 0
does not work). Here is the solution I stumbled upon:
public class Solution {
public int power(String A) {
String dividend = A;
StringBuilder str;
if (A == null || A.length() == 0)
return 0;
if (A.length() == 1 && A.charAt(0) == '0')
return 0;
while (dividend.length() > 0 && !dividend.equalsIgnoreCase("2")) {
str = new StringBuilder();
int carry = 0;
int n = dividend.length();
if (n > 0) {
int num = dividend.charAt(n - 1) - '0';
if (num % 2 == 1)
return 0;
}
for (int i = 0; i < n; i++) {
char c = (char) (dividend.charAt(i) - '0');
int res = c + 10 * carry;
c = (char) (res / 2 + '0');
carry = res % 2;
str.append(c);
}
if (str.charAt(0) == '0')
str.deleteCharAt(0);
dividend = str.toString();
}
return 1;
}
}
I am having problems understanding the solution. The first check is done if a number is odd or not. I am having problems understanding the implementation of the manual division done in this problem (especially the arithmetic operations involving both char and int). I get that '0' == 48
and subtracting '0'
from a character converts it into integer value. Can anyone explain to me how this division operation has been implemented here? Thanks!