476. Number Complement
来源:互联网 发布:c语言三个数排序 编辑:程序博客网 时间:2024/06/07 09:28
问题:
Given a positive integer, output its complement number. The complement strategy is to flip the bits of its 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: 5Output: 2Explanation: 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: 1Output: 0Explanation: The binary representation of 1 is 1 (no leading zero bits), and its complement is 0. So you need to output 0.解释:
分析:
1.先将一个十进制数转化为二进制,求反码后转化为十进制
int ans = 0;StringBuffer buffer = new StringBuffer();while (num > 0) {if (num % 2 == 1)buffer.insert(0, 0);elsebuffer.insert(0, 1);num /= 2;}int m = 0;while (m < buffer.length()) {ans = ans * 2 + buffer.charAt(m) - '0';m++;}return ans;
2.利用规律 101+010+1=1000
public int findComplement(int num) {int ans = 0; int cp=num; int m=1; while(cp!=0){ cp=cp/2;m=m*2; } ans=m-1-num; return ans; }
0 0
- LeetCode 476. Number Complement
- leetcode 476. Number Complement
- 【Leetcode】476. Number Complement
- 【Leetcode】476. Number Complement
- 476. Number Complement*
- LeetCode 476. Number Complement
- LeetCode 476. Number Complement
- LeetCode--476. Number Complement
- LeetCode 476. Number Complement
- 476. Number Complement
- 476. Number Complement [LeetCode]
- 476. Number Complement
- [LeetCode]476.Number Complement
- 476. Number Complement
- 【LeetCode】 476. Number Complement
- LeetCode 476. Number Complement
- 476. Number Complement
- 476. Number Complement (E)
- HDU-4507 吉哥系列故事――恨7不成妻 (数位dp)
- 用LabVIEW连接USB相机采集一幅图像
- html上的数据怎么交给php处理
- 安卓adb命令中pm工具的作用及用法详解
- Codeforces Round #396 (Div. 2) A+B
- 476. Number Complement
- 统计增加一个平均时间字段
- wordpress配置HTTPS遇到问题解决方案
- 利用TraceView优化自己的代码
- Android之ContentProvider详解
- 用CPU来加速你的Linux命令
- HDOJ(HDU).1258 Sum It Up (DFS)
- P1427 小鱼的数字游戏
- BZOJ 1014, 火星人