国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

[LeetCode] Hamming Distance(二進制中有多少個1)+ Number Complement(補碼)

2019-11-08 18:35:57
字體:
來源:轉載
供稿:網友

啊,又是好久沒來了!

最近又開始刷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 ≤ xy < 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
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 林周县| 龙口市| 会昌县| 上杭县| 宜春市| 琼海市| 裕民县| 古浪县| 启东市| 积石山| 武城县| 天等县| 昌邑市| 皋兰县| 隆德县| 资溪县| 永清县| 沾益县| 淮北市| 华阴市| 夏河县| 河北省| 维西| 城步| 登封市| 青海省| 临江市| 德保县| 南溪县| 拜泉县| 高淳县| 邻水| 兴隆县| 郎溪县| 长春市| 南丰县| 赣州市| 兖州市| 万宁市| 共和县| 德保县|