Power of 2
int comp(string B, string A){
if(B.size() == A.size())
return (B < A ? -1 : B > A ? 1 : 0);
return (B.size() < A.size() ? -1 : 1);
}
string timesTwo(string B) {
reverse(B.begin(), B.end());
int carry = 0;
string res = "";
int i = 0;
while(i < B.size()) {
int prod = (B[i] - '0') * 2 + carry;
res.push_back((prod % 10) + '0');
carry = prod / 10;
i++;
}
while(carry) {
res.push_back((carry % 10) + '0');
carry /= 10;
}
reverse(res.begin(), res.end());
return res;
}
int Solution::power(string A) {
// edge case
if(A == "1" || A[0] == '-')
return 0;
string B = "1";
while(comp(B, A) == -1)
B = timesTwo(B);
return (comp(B, A) == 0);
}
Time Complexity: β
Space Complexity: β for products of β.
Edge Cases:
You initialized
res = 1
But is β being equal to given number a valid case?What if the input is negative?
Last updated