- for clause judges the each bit in a 16-bit binary number.
- In the for loop, we use
&
and<<
. The effect of<<
operation is like this: wheni = 15
,(1 << i)
will convert0000000000000001
into1000000000000000
; and wheni = 10
, the result will be0000010000000000
. So the result ofnum &(1 << i
is comparing theith
digit (i
is from 0 to 15) innum
with(1 << i)
. Only whenith
digit innum
is1
, cannum &(1 << i)
be true.
1 |
public String (int num) { |
LeetCode Example 1 - Number of 1 Bits
https://leetcode.com/problems/number-of-1-bits/
Write a function that takes an unsigned integer and returns the number of
1
bits it has (also known as the Hamming weight).For example, the 32-bit integer
11
has binary representation00000000000000000000000000001011
, so the function should return 3.
Solution 1
1 |
public class Solution { |
Solution 2 O(logN)
1 |
public class Solution { |
The time complexity is O(logN), Since for each >>
operation, N
will be N / 2
.
Solution 3 O(countOnes(N))
1 |
public class Solution { |
For an arbitrary n, we can convert it to a binary number which is xxx...xxx1000....000
. We do not take of how many x
there are and how many 1
s in the sequence of x
, we just focus on 1000...000
.
Since n is xxx...xxx1000....000
, then n - 1 must be xxx...xxx0111....111
with the same numbers of digits after xxx...xxx
. When we use (n & (n - 1))
operation, we will get xxx...xxx0000....000
, which means we remove the last 1
in n
.
LeetCode Example 2 - Reverse Bits
https://leetcode.com/problems/reverse-bits/
Reverse bits of a given 32 bits unsigned integer.
For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represented in binary as 00111001011110000010100101000000).
Follow up:
If this function is called many times, how would you optimize it?
1 |
public class Solution { |
近期评论