|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 zltzlt 于 2020-1-30 13:10 编辑
0 ms,写得略显复杂
- #include <string>
- #include <cmath>
- using namespace std;
- string dec2bin(int num)
- {
- string res = "";
- while (num)
- {
- if (num % 2)
- res = "1" + res;
- else
- res = "0" + res;
- num /= 2;
- }
- return res;
- }
- string invert(string str)
- {
- int i;
- string res = "";
- for (i = 0; i < str.size(); i++)
- {
- if (str[i] == '0')
- res += "1";
- else
- res += "0";
- }
- return res;
- }
- int count(string str, char ch)
- {
- int res = 0, i;
- for (i = 0; i < str.size(); i++)
- {
- if (str[i] == ch)
- res++;
- else
- break;
- }
- return res;
- }
- int bin2dec(string bin)
- {
- int res = 0, i, j = 0;
- if (bin[0] == '0')
- bin.erase(0, count(bin, '0'));
- for (i = (bin.size() - 1); i >= 0; i--)
- {
- if (bin[j++] == '1')
- {
- res += int(pow(2, i));
- }
- }
- return res;
- }
- class Solution {
- public:
- int findComplement(int num) {
- return bin2dec(invert(dec2bin(num)));
- }
- };
复制代码 |
|