啊,又是好久沒來了!
最近又開始刷leetcode,發現題目多了不少。還是從基礎開始做吧。
這里是兩道關于位運算的題。
1. Hamming Distance
題目鏈接在此
The Hamming distance between two integers is the number of positions at which the corresponding bits are different.
Given two integers x and y, calculate the Hamming distance.
Note:0 ≤ x, y < 231.
Example:
Input: x = 1, y = 4Output: 2Explanation:1 (0 0 0 1)4 (0 1 0 0) ↑ ↑The above arrows point to positions where the corresponding bits are different.就是數一下兩個二進制數之間有位數有區別。很簡單,先異或,再數有多少個1。
輸多少個1那一步,我寫的這篇博客有。
這里是我在不記得大神的做法的情況下,自己寫的(3ms):
class Solution {public: int hammingDistance(int x, int y) { int a = x ^ y; int count = 0; while (a != 0) { count += (a & 1); a >>= 1; } return count; }};2. Number Complement
題目鏈接在此Given a positive integer, output its complement number. The complement strategy is to flip the bits of its binary rePResentation.
Note:
The given integer is guaranteed to fit within the range of a 32-bit signed integer.You could assume no leading zero bit in the integer’s binary representation.Example 1:
Input: 5Output: 2Explanation: The binary representation of 5 is 101 (no leading zero bits), and its complement is 010. So you need to output 2.Example 2:
Input: 1Output: 0Explanation: The binary representation of 1 is 1 (no leading zero bits), and its complement is 0. So you need to output 0.補碼定義為二進制每位都翻轉后得到的數字。這是我寫的,就是先算出這個數的二進制有多少位,然后用這么多位的1跟他做異或。比如2的二進制是10,有兩位, 就拿11和10做異或,得到01。顯然比較慢:class Solution {public: int findComplement(int num) { int n = num; int bits = 0; while(n) { bits++; n >>= 1; } return num ^ int(pow(2.0, bits) - 1); }};這是discuss里的大神的做法:class Solution {public: int findComplement(int num) { unsigned mask = ~0; while (num & mask) mask <<= 1; return ~mask & ~num; }};例子:num = 00000101mask = 11111000~mask & ~num = 00000010
新聞熱點
疑難解答