【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)。
相關文章
- 【Lintcode】1665. Calculate Number
- 【Lintcode】1562. Number of RestaurantsREST
- [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
- 【Lintcode】191. Maximum Product Subarray