?LeetCode刷題實(shí)戰(zhàn)477:漢明距離總和
The Hamming distance between two integers is the number of positions at which the corresponding bits are different.
Given an integer array nums, return the sum of Hamming distances between all the pairs of the integers in nums.
示例? ? ? ? ? ? ? ? ? ? ? ? ?
示例 1:
輸入:nums = [4,14,2]
輸出:6
解釋?zhuān)涸诙M(jìn)制表示中,4 表示為 0100 ,14 表示為 1110 ,2表示為 0010 。(這樣表示是為了體現(xiàn)后四位之間關(guān)系)
所以答案為:
HammingDistance(4, 14) + HammingDistance(4, 2) + HammingDistance(14, 2) = 2 + 2 + 2 = 6
示例 2:
輸入:nums = [4,14,4]
輸出:4
解題
class?Solution?{
public:
????int?totalHammingDistance(vector<int>& nums)?{
????????int?cnt,ans=0;
????????for(int?i=0;i<32;i++){
????????????cnt=0;
????????????for(int?j=0;j????????????????if(nums[j]&1){
????????????????????cnt++;
????????????????}
????????????????nums[j]>>=1;
????????????}
????????????ans+=cnt*(nums.size()-cnt);
????????}
????????return?ans;
????}
};
LeetCode1-460題匯總,希望對(duì)你有點(diǎn)幫助!
LeetCode刷題實(shí)戰(zhàn)461:漢明距離
LeetCode刷題實(shí)戰(zhàn)462:最少移動(dòng)次數(shù)使數(shù)組元素相等 II
LeetCode刷題實(shí)戰(zhàn)463:島嶼的周長(zhǎng)
LeetCode刷題實(shí)戰(zhàn)464:我能贏嗎
LeetCode刷題實(shí)戰(zhàn)465:最優(yōu)賬單平衡
LeetCode刷題實(shí)戰(zhàn)466:統(tǒng)計(jì)重復(fù)個(gè)數(shù)
LeetCode刷題實(shí)戰(zhàn)467:環(huán)繞字符串中唯一的子字符串
LeetCode刷題實(shí)戰(zhàn)468:驗(yàn)證IP地址
LeetCode刷題實(shí)戰(zhàn)469:凸多邊形
LeetCode刷題實(shí)戰(zhàn)470:用 Rand7() 實(shí)現(xiàn) Rand10()
LeetCode刷題實(shí)戰(zhàn)471:編碼最短長(zhǎng)度的字符串
LeetCode刷題實(shí)戰(zhàn)472:連接詞
LeetCode刷題實(shí)戰(zhàn)473:火柴拼正方形
LeetCode刷題實(shí)戰(zhàn)474:一和零
LeetCode刷題實(shí)戰(zhàn)475:供暖器
LeetCode刷題實(shí)戰(zhàn)476:數(shù)字的補(bǔ)數(shù)
