Leetcode刷题(3)
来源:互联网 发布:nginx停止命令 编辑:程序博客网 时间:2024/06/05 08:16
Given a positive integer,output its complement number. The complement strategy is to flip the bits ofits binary representation.
Note:
- The given integer is guaranteed to fit within the range of a 32-bit signed integer.
- You could assume no leading zero bit in the integer’s binary representation.
Example 1:
Input: 5
Output: 2
Explanation: The binary representation of 5 is 101 (no leading zero bits), and its complement is 010. So you need to output 2.
Example 2:
Input: 1
Output: 0
Explanation: The binary representation of 1 is 1 (no leading zero bits), and its complement is 0. So you need to output 0.
Subscribe tosee which companies asked this question.
我的解答:
classSolution {
public:
int findComplement(int num) {
int a[32];
int b[32];
int find = 0;
int i = 0;
while(num != 0) {
a[i] = num % 2;
b[i] = 1 - a[i];
num = num - a[i];
num = num / 2;
i++;
}
for(int j=0; j<i; j++) {
find = find + b[j]*pow(2,j);
}
return find;
}
};
比较经典的答法:
classSolution {
public:
int findComplement(int num) {
unsigned mask = ~0;
while (num & mask) mask <<=1; //还未理解这块
//比如101
//那mask应该是11111100,为什么是11111000?
return ~mask & ~num;
}
};
For example,
num = 00000101mask = 11111000~mask & ~num = 00000010
- LeetCode刷题(3)
- Leetcode刷题(3)
- LeetCode刷题(3)
- 【leetcode】leetcode 刷题 笔记 (不定期更新)
- Leetcode 刷题: 3Sum
- leetcode刷题-堆栈3
- leetcode刷题(Python)
- LeetCode刷题(1)
- LeetCode刷题(2)
- LeetCode刷题(废弃)
- LeetCode刷题(FizzBuzz)
- Leetcode刷题(1)
- Leetcode刷题(2)
- Leetcode刷题(4)
- Leetcode刷题(5)
- Leetcode刷题(6)
- Leetcode刷题(7)
- Leetcode刷题(13)
- java Spring AOP 面向切面编程 概念辅助理解记忆
- Linux下安装JDK7
- Java面试题全集(11)
- 安卓开发之——第一个程序HelloWorld!
- 算法设计与应用基础
- Leetcode刷题(3)
- 求A的B次方的最后三位整数
- sock_common
- Kafka Protocal Guide
- Hibernate的主配置文件hibernate.cfg.xml
- java 使用正则表达式统计一个字符串中子字符串出现次数
- eclipse 配置c/c++环境的Launch failed,Binary not found错误
- 002
- sk_buff_head