What is the space complexity for this solution? This code reverses the bits of a 32 bit unsigned integer. I am unsure as to whether the space is O(N) because a copy all bits are made before returning the answer, or if this is considered O(1) since the size of the answer is not dependent on the size of the input A.
unsigned int Solution::reverse(unsigned int A) {
unsigned int ans = 0;
for (unsigned int i = 0; i < 32 ; ++i) {
if (A & (1 << i)) {
ans += (1 << (31-i));
}
}
return ans;
}
If we try to analyze line by line your code :
unsigned int Solution::reverse(unsigned int A) {
unsigned int ans = 0; // O(1)
for (unsigned int i = 0; i < 32 ; ++i) { // O(1)
if (A & (1 << i)) { // O(1)
ans += (1 << (31-i)); // O(1)
}
}
return ans;
}
Every operation you make is linear. It does not depend on any parameter you give since an unsigned int has a fixed size. According to me, your method is in O(1).
If I may suggest : you should avoid harcoding the value 32 in your code and replace it with sizeof(A)*8
which should be more portable. sizeof()
return the size in byte of an object. More information here.