https://leetcode.com/problems/complement-of-base-10-integer/

Every non-negative integer N has a binary representation.  For example, 5 can be represented as "101" in binary, 11 as "1011" in binary, and so on.  Note that except for N = 0, there are no leading zeroes in any binary representation.

The complement of a binary representation is the number in binary you get when changing every 1 to a 0 and 0 to a 1.  For example, the complement of "101" in binary is "010" in binary.

For a given number N in base-10, return the complement of it's binary representation as a base-10 integer.

Example 1:

Input: 5
Output: 2
Explanation: 5 is "101" in binary, with complement "010" in binary, which is 2 in base-10.

Example 2:

Input: 7
Output: 0
Explanation: 7 is "111" in binary, with complement "000" in binary, which is 0 in base-10.

Example 3:

Input: 10
Output: 5
Explanation: 10 is "1010" in binary, with complement "0101" in binary, which is 5 in base-10.

代码:

class Solution {
public:
int bitwiseComplement(int N) {
if(N == 0) return 1;
vector<int> ans;
while(N) {
ans.push_back(!(N % 2));
N /= 2;
}
int sum = 0;
for(int i = 0; i < ans.size() / 2; i ++)
swap(ans[i], ans[ans.size() - i - 1]);
for(int i = 0; i < ans.size(); i ++)
sum += ans[i] * pow(2, ans.size() - 1 - i); return sum;
}
int pow(int a, int b) {
int ans = 1;
while(b) {
if(b % 2) {
ans *= a;
b --;
} else {
a *= a;
b /= 2;
}
}
return ans;
}
};

  周末开始啦 

最新文章

  1. worktile的架构设计
  2. python 调用 shell 命令方法
  3. 10个鲜为人知的WordPress函数
  4. tomcat学习笔记1
  5. c++中类长度解析
  6. HDU 4746 Mophues 莫比乌斯反演
  7. Linux的前世今生
  8. Hide a file in a picture
  9. DevExpress ASP.NET 使用经验谈(8)-ASPxGridView自定义列和基本事件
  10. 未来手机Alo即将问世!全息投影手机的新高峰!全息3d 网
  11. 关于MUI集成微信分享遇到的坑
  12. 【ThinkPHP框架学习 】(2) --- 后台管理系统如何用iframe点击左边右边局部刷新
  13. 一个清除Xcode项目占用大量空间的脚本
  14. 瑞芯微RKnanC芯片处理器介绍
  15. 三分钟了解Go语言的前世今生
  16. Linux colrm命令详解
  17. Mac/Linux/Centos终端中上传文件到Linux云服务器
  18. OSPF协议之详细图解
  19. [C#]WinForm 中 comboBox控件之数据绑定
  20. mongodb基础学习4-游标

热门文章

  1. C# -- 正则表达式匹配字符之含义
  2. gcc5.4报错对‘std::__cxx11::basic_string&lt;char, std::char_traits&lt;char&gt;, std::allocator&lt;char&gt; &gt;::~basic_string()’未定义的引用
  3. C#批量向数据库插入数据
  4. 远程连接ubuntu的MongoDB遇到的坑
  5. ubuntu下安裝sogou拼音
  6. 笔记-Android中打开各种格式的文件(apk、word、excel、ppt、pdf、音视频、图片等)
  7. css样式的书写顺序及原理
  8. [CQOI2018]破解D-H协议
  9. No.3
  10. Linux 通过rinetd端口转发来访问内网服务