LeetCode 题解之Number Complement

1、题目描述

2、题目分析

使用 C++的 bitset 库进行操作;

3、代码

 1 int findComplement(int num) {
 2        bitset<32> b(num);
 3         string s = b.to_string();
 4         string::iterator it = s.begin() ;
 5         while( it != s.end() ){
 6             if( *it != '0' ) break;
 7             ++it;
 8         }
 9         if( it == s.end() ){
10             s = "0";
11         }else{
12             s.assign(it,s.end());
13         }
14         
15         it = s.begin() ;
16         while( it != s.end() ){
17             *it = ( *it == '0' )?'1':'0';
18             ++it;
19         }
20         
21         bitset<32> bs(s);
22         return bs.to_ulong() ;
23     }

猜你喜欢

转载自www.cnblogs.com/wangxiaoyong/p/9303252.html