【Lintcode】1665. Calculate Number
題目地址:
https://www.lintcode.com/problem/calculate-number/description
給定一個十進位制數 x x x,先將其轉化為二進位制,然後返回一個陣列 A A A,使得 A [ 0 ] A[0] A[0]是其二進位制表示一共多少個 1 1 1,後面依次是 x x x從左到右第幾個數是 1 1 1,從 1 1 1開始計數。
程式碼如下:
import java.util.ArrayList;
import java.util.List;
public class Solution {
/**
* @param num: the num
* @return: the array subject to the description
*/
public int[] calculateNumber(int num) {
// Write your code here.
int pos = 0;
List<Integer> list = new ArrayList<>();
while (num != 0) {
if ((num & 1) == 1) {
list.add(pos);
}
num >>= 1;
pos++;
}
int[] res = new int[list.size() + 1];
res[0] = list.size();
for (int i = 0; i < list.size(); i++) {
res[i + 1] = list.get(list.size() - 1) - list.get(list.size() - 1 - i) + 1;
}
return res;
}
}
時空複雜度 O ( log x ) O(\log x) O(logx)。
相關文章
- 【Lintcode】1562. Number of RestaurantsREST
- 【Lintcode】1218. Number Complement
- 【Calculate】Calculate Linux安裝操作記錄Linux
- [LintCode] Daily TemperaturesAI
- [LintCode] Permutation in String
- [LintCode/LeetCode] Meeting RoomsLeetCodeOOM
- Lintcode 1263. Is Subsequence
- 【Lintcode】1189. Minesweeper
- JavaScript Number()JavaScript
- [LeetCode/LintCode] Largest Palindrome ProductLeetCode
- [LintCode/LeetCode] Contains Duplicate IIILeetCodeAI
- [LintCode] Check Full Binary Tree
- [LintCode/LeetCode] Remove Duplicate LettersLeetCodeREM
- [LintCode] 3Sum Smaller
- 【Lintcode】1615. The Result of Investment
- [LintCode] Binary Tree Level Order
- 【Lintcode】1736. Throw Garbage
- 【Lintcode】1789. Distinguish UsernameNGUI
- 【Lintcode】576. Split Array
- 【Lintcode】1267. Lexicographical Numbers
- 【Lintcode】141. Sqrt(x)
- 【Lintcode】1415. Residual Product
- 【Lintcode】1230. Assign CookiesCookie
- 【Lintcode】1732. Snakes and Ladders
- 【Lintcode】1850. Pick ApplesAPP
- 【Lintcode】572. Music PairsAI
- 【Lintcode】318. Character Grid
- 【Lintcode】1891. Travel Plan
- Kata:Hamming number
- JavaScript Number toLocaleString()JavaScript
- JavaScript Number toString()JavaScript
- Number.NaNNaN
- JavaScript Number 物件JavaScript物件
- Leetcode Number of islandsLeetCode
- [LintCode/LeetCode] Check Sum of K PrimesLeetCode
- [LintCode]NumberofIslands(島嶼個數)
- lintcode-514-柵欄染色
- 【Lintcode】1322. Product Equal B