鱼C论坛

 找回密码
 立即注册
查看: 1337|回复: 0

[技术交流] LeetCode 476. 数字的补数

[复制链接]
发表于 2020-1-30 13:09:08 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
本帖最后由 zltzlt 于 2020-1-30 13:10 编辑

0 ms,写得略显复杂

  1. #include <string>
  2. #include <cmath>

  3. using namespace std;

  4. string dec2bin(int num)
  5. {
  6.     string res = "";
  7.     while (num)
  8.     {
  9.         if (num % 2)
  10.             res = "1" + res;
  11.         else
  12.             res = "0" + res;
  13.         num /= 2;
  14.     }
  15.     return res;
  16. }

  17. string invert(string str)
  18. {
  19.     int i;
  20.     string res = "";
  21.     for (i = 0; i < str.size(); i++)
  22.     {
  23.         if (str[i] == '0')
  24.             res += "1";
  25.         else
  26.             res += "0";
  27.     }
  28.     return res;
  29. }

  30. int count(string str, char ch)
  31. {
  32.     int res = 0, i;
  33.     for (i = 0; i < str.size(); i++)
  34.     {
  35.         if (str[i] == ch)
  36.             res++;
  37.         else
  38.             break;
  39.     }
  40.     return res;
  41. }

  42. int bin2dec(string bin)
  43. {
  44.     int res = 0, i, j = 0;
  45.     if (bin[0] == '0')
  46.         bin.erase(0, count(bin, '0'));
  47.     for (i = (bin.size() - 1); i >= 0; i--)
  48.     {
  49.         if (bin[j++] == '1')
  50.         {
  51.             res += int(pow(2, i));
  52.         }
  53.     }
  54.     return res;
  55. }

  56. class Solution {
  57. public:
  58.     int findComplement(int num) {
  59.         return bin2dec(invert(dec2bin(num)));
  60.     }
  61. };
复制代码

本帖被以下淘专辑推荐:

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-5-1 14:43

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表