※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1693559225.A.700.html
Re: [閒聊] 每日LeetCode
看板 | Marginalman |
---|---|
作者 | Rushia (みけねこ的鼻屎) |
時間 | 2023-09-01 17:06:59 |
留言 | 0則留言 |
https://i.imgur.com/tdaniED.jpg
--
※ 批踢踢實業坊(ptt.cc), 來自: 122.100.73.13 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1693559225.A.700.html
338. Counting Bits
給你一個數字 n ,返回一個陣列包含了從數字 0 ~ n 的二進位分別有幾個 1。
Example 1:
Input: n = 2
Output: [0,1,1]
Explanation:
0 --> 0
1 --> 1
2 --> 10
Example 2:
Input: n = 5
Output: [0,1,1,2,1,2]
Explanation:
0 --> 0
1 --> 1
2 --> 10
3 --> 11
4 --> 100
5 --> 101
思路:
1.遍歷 0 到 n 然後 count 有幾個 1 就好。
Java Code:
---------------------------------
class Solution {
public int[] countBits(int n) {
int[] res = new int[n + 1];
for (int i = 0; i <= n; i++) {
res[i] = bitCount(i);
}
return res;
}
private int bitCount(int n) {
int cnt = 0;
while (n != 0) {
cnt += n % 2;
n = n >>> 1;
}
return cnt;
}
}
---------------------------------
--
※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1693559225.A.700.html