【Lintcode】1218. Number Complement
題目地址:
https://www.lintcode.com/problem/number-complement/description
給定一個正整數 x x x,輸出其補數。補數定義是將 x x x的二進位制表示位按位翻轉所得之數(該二進位制表示不應該含前導 0 0 0,除非它自己是 0 0 0)。
可以先求一下 x x x的二進位制表示的長度(去掉所有前導 0 0 0,除非它自己是 0 0 0),設長度是 l l l,則答案就是 ( 1 < < l ) − 1 − x (1<<l)-1-x (1<<l)−1−x。程式碼如下:
public class Solution {
/**
* @param num: an integer
* @return: the complement number
*/
public int findComplement(int num) {
// Write your code here
int len = 0, tmp = num;
while (tmp != 0) {
len++;
tmp >>= 1;
}
return (1 << len) - 1 - num;
}
}
時間複雜度 O ( log x ) O(\log x) O(logx),空間 O ( 1 ) O(1) O(1)。
相關文章
- 【LeetCode】476.Number Complement_EASY(二)LeetCode
- LintCode-Majority Number
- LintCode-Majority Number II
- LintCode-Majority Number III
- 【Lintcode】1562. Number of RestaurantsREST
- 【Lintcode】1665. Calculate Number
- LintCode-Kth Prime Number.
- 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
- 【Lintcode】576. Split Array
- 【Lintcode】1736. Throw Garbage
- LintCode - A + B 問題(普通)
- Lintcode 反轉整數