zoukankan      html  css  js  c++  java
  • 461.汉明距离(c++实现)

    问题描述:

    两个整数之间的汉明距离指的是这两个数字对应二进制位不同的位置的数目。

    给出两个整数 x 和 y,计算它们之间的汉明距离。

    注意:
    0 ≤ xy < 231.

    示例:

    输入: x = 1, y = 4
    
    输出: 2
    
    解释:
    1   (0 0 0 1)
    4   (0 1 0 0)
           ↑   ↑
    
    上面的箭头指出了对应二进制位不同的位置。
    实现方法:
    class Solution {
    public:
        int hammingDistance(int x, int y) {
            int count=0;
            vector<int> a;
            vector<int> b;
            if(x==0&&y==0)
                return 0;
            else if(x==0&&y!=0)
            {
                while(y)
                {
                    int temp=y%2;
                    b.push_back(temp);
                    y=y/2;
                    if(temp==1)
                        count++;
                }
            }
            else if(x!=0&&y==0)
            {
                while(x)
                {
                    int temp1=x%2;
                    a.push_back(temp1);
                    x=x/2;
                    if(temp1==1)
                        count++;
                }
                
            }
            else
            {
                while(y)
                {
                    int temp=y%2;
                    b.push_back(temp);
                    y=y/2;
                
                }
                   while(x)
                {
                    int temp1=x%2;
                    a.push_back(temp1);
                    x=x/2;
                   
                }
               
                int jishu=max(a.size(),b.size());  
                 if(jishu>a.size())
                 {  
                     int bb=a.size();
                     for(int hh=0;hh<jishu-bb;hh++)
                     {
                         a.push_back(0);
                     }
                 }
                else
                {
                    int aa=b.size(); 
                    for(int h=0;h<jishu-aa;h++)
                     {
                         b.push_back(0);
                     }
                }
                for(int kk=0;kk<jishu;kk++)
                {
                    if(a[kk]+b[kk]==1)
                        count++;
    
                }
            }
             return count;
        }
    };
  • 相关阅读:
    20150607-0608
    20150423
    感触
    NSString里面的数字
    Git使用相关
    状态栏的设置
    UI相关问题
    分栏(标签)控制器
    导航控制器
    NSAttributedString 属性
  • 原文地址:https://www.cnblogs.com/mydomain/p/9983224.html
Copyright © 2011-2022 走看看