LeetCode题解之Hamming Distance

1、题目描述

2、问题分析

使用C++ 标准库中的 bitset 类,将整数转换为二进制形式,然后再将其转换为字符串,最后比较字符串。

3、代码

 1 int hammingDistance(int x, int y) {
 2         
 3         bitset<32> a(x);
 4         bitset<32> b(y);
 5         
 6         string a_s = a.to_string();
 7         string b_s = b.to_string();
 8         
 9         string::iterator it1 = a_s.begin() ;
10         string::iterator it2 = b_s.begin() ;
11         int re = 0;
12         while( it1 != a_s.end() && it2 != b_s.end() ){
13             if( *it1 != *it2 ){
14                 re++;
15             }
16             it1++;
17             it2++;
18         }
19         return re;
20     }

 

posted @ 2018-07-11 17:11  山里的小勇子  阅读(127)  评论(0编辑  收藏  举报