#Leetcode# 1009. Complement of Base 10 Integer
2024-10-07 22:07:30
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;
}
};
周末开始啦
最新文章
- worktile的架构设计
- python 调用 shell 命令方法
- 10个鲜为人知的WordPress函数
- tomcat学习笔记1
- c++中类长度解析
- HDU 4746 Mophues 莫比乌斯反演
- Linux的前世今生
- Hide a file in a picture
- DevExpress ASP.NET 使用经验谈(8)-ASPxGridView自定义列和基本事件
- 未来手机Alo即将问世!全息投影手机的新高峰!全息3d 网
- 关于MUI集成微信分享遇到的坑
- 【ThinkPHP框架学习 】(2) --- 后台管理系统如何用iframe点击左边右边局部刷新
- 一个清除Xcode项目占用大量空间的脚本
- 瑞芯微RKnanC芯片处理器介绍
- 三分钟了解Go语言的前世今生
- Linux colrm命令详解
- Mac/Linux/Centos终端中上传文件到Linux云服务器
- OSPF协议之详细图解
- [C#]WinForm 中 comboBox控件之数据绑定
- mongodb基础学习4-游标
热门文章
- C# -- 正则表达式匹配字符之含义
- gcc5.4报错对‘std::__cxx11::basic_string<;char, std::char_traits<;char>;, std::allocator<;char>; >;::~basic_string()’未定义的引用
- C#批量向数据库插入数据
- 远程连接ubuntu的MongoDB遇到的坑
- ubuntu下安裝sogou拼音
- 笔记-Android中打开各种格式的文件(apk、word、excel、ppt、pdf、音视频、图片等)
- css样式的书写顺序及原理
- [CQOI2018]破解D-H协议
- No.3
- Linux 通过rinetd端口转发来访问内网服务