[InterviewBit] Power of 2

Power of 2

  • Time :
  • Space :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
int Solution::power(string A) {
if(A == "1") return 0;
while((A.back() - '0') % 2 == 0) {
string B = "";
int carry = A[0] == '1' ? 1 : 0;
for(int i = A[0] == '1' ? 1 : 0; i < A.length(); i++) {
int now = carry * 10 + A[i] - '0';
char ch = now / 2 + '0';
B.push_back(ch);
carry = now % 2;
}
swap(A,B);
}
return A == "1";
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/10/06/PS/interviewbit/power-of-2/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.