【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)。
相關文章
- Calculate the Number of IOPS and Throughput of a Database with AWRDatabase
- LintCode-Majority Number
- LintCode-Majority Number II
- LintCode-Majority Number III
- 【Lintcode】1562. Number of RestaurantsREST
- LintCode-Kth Prime Number.
- 【Lintcode】1218. Number Complement
- 【Calculate】Calculate Linux安裝操作記錄Linux
- How to calculate the sale order item costs?
- Shell Script to Calculate Values Recommended Linux HugePagesLinux
- ZOJ 3772 Calculate the Function(線段樹+矩陣)Function矩陣
- JavaScript Number()JavaScript
- [LintCode] Daily TemperaturesAI
- LintCode 子樹
- LintCode-Backpack
- LintCode-HeapifyAPI
- Oracle System Change Number (SCN) Number 完全筆記Oracle筆記
- 【NUMBER】Oracle的NUMBER資料型別特點Oracle資料型別
- [LintCode] Permutation in String
- LintCode 主元素 II
- LintCode 解碼方法
- LintCode-Search for a Range
- LintCode-K Sum
- LintCode-Word SegmentationSegmentation
- LintCode-Hash FunctionFunction
- LintCode-Fast PowerAST
- Lintcode-Max Tree
- LintCode-Partition Array
- LintCode-Subarray Sum
- LintCode-A+B Problem
- LintCode-BackPack II
- LintCode-Previous Permuation
- LintCode 字串比較字串
- JavaScript Number 物件JavaScript物件
- Number.NaNNaN
- Number of BoomerangsOOM
- [LintCode] 3Sum Smaller
- 【Lintcode】572. Music PairsAI