Problem
Counting the number of 1 bits in the binary representation of a given integer.
Analysis
Method 1:
- shift the number right by one bit each time, and check whether the right-most bit is 1
- If yes, count++
Method 2:
- if n is not 0, count++
- assign n = n & (n-1), repeat until n is 0
Time complexity
- method 1: theta(n)
- method 2: O(n)
Code
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// method 1 | |
int countNumOfOnes(int n){ | |
int count = 0; | |
while(n){ | |
count += (n & 1); | |
n >> 1; | |
} | |
return count; | |
} | |
// method 2 | |
int countNumOfOnes(int n){ | |
int count = 0; | |
while(n){ | |
n &= (n-1); | |
count++; | |
} | |
return count; | |
} |
Reference
No comments:
Post a Comment