Re: [閒聊] 每日LeetCode已回收

看板Marginalman作者 (みけねこ的鼻屎)時間2年前 (2023/09/01 17:07), 2年前編輯推噓0(001)
留言1則, 1人參與, 2年前最新討論串403/719 (看更多)
https://leetcode.com/problems/counting-bits/description/ 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://i.imgur.com/tdaniED.jpg
-- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 122.100.73.13 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1693559225.A.700.html

09/01 17:08, 2年前 , 1F
大師
09/01 17:08, 1F
※ 編輯: Rushia (122.100.73.13 臺灣), 09/01/2023 17:08:43
文章代碼(AID): #1ayQcvS0 (Marginalman)
討論串 (同標題文章)
文章代碼(AID): #1ayQcvS0 (Marginalman)