LeetCode 461. 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 = 4

Output: 2

Explanation:
1   (0 0 0 1)
4   (0 1 0 0)
       ↑   ↑

The above arrows point to positions where the corresponding bits are different.
class Solution {
public:
    string to_str(int x){
        string s;
        if(x==0) return "0";
        while(x!=0){
            char c='0'+x%2;
            s.insert(s.begin(),c);
            x/=2;
        }
        return s;
    }
    int hammingDistance(int x, int y) {
        string s1=to_str(x),s2=to_str(y);
        int len=max(s1.size(),s2.size());
        s1.insert(s1.begin(),len-s1.size(),'0');
        s2.insert(s2.begin(),len-s2.size(),'0');
        int cnt=0;
        for(int i=0;i<s1.size();i++)
            if(s1[i]!=s2[i])
                cnt++;
        return cnt;
    }
};
posted @ 2018-12-04 21:30  A-Little-Nut  阅读(84)  评论(0编辑  收藏  举报