zoukankan      html  css  js  c++  java
  • 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;
        }
    };
    
  • 相关阅读:
    多线程
    带缓存的字符输入输出流
    输入输出流(I/O)
    课本235页2-3题
    包装&工具类
    集合类SetMap
    tp框架之增删改查
    tp框架之数据添加
    tp框架之查询
    tp框架之Model类与命名空间
  • 原文地址:https://www.cnblogs.com/A-Little-Nut/p/10067320.html
Copyright © 2011-2022 走看看