This question is really about meaning of N in big O notation, not complexity of algorithm.
N means size of the data. But in case where where "data" is a single number you need to define what you understand as size of data. The value of a number or length of it's representation.
IMO the algorithm is O(N). Because in this problem of counting 1 in binary representation IMO relevant size of data is length of the number's representation, not it's value i.e. the length of the bit stream. And obvious worst case is all 1's taking N iterations.
But if you consider value of N as size of the data, it's representation has log(N) length so you can say it's O(log(N))
PS Also big O notation makes sense only if you generalise algorithm for arbitrarily high Ns. In this code N is limited by int size, so you can say it's O(1) as it will be at most 64 loop iterations (for 64 bit ints)
while( n!=0 )
. Otherwise negative numbers won't be counted properly. – TruthfulN
is the number of bits, then it isO(N)
, but ifN
isn
, then it isO(log N)
– Magen