476. Number Complement
来源:互联网 发布:智能app软件下载 编辑:程序博客网 时间:2024/05/28 05:18
Given a positive integer, output itscomplement number. The complement strategy is to flip the bits of its binaryrepresentation.
Note:
The given integer is guaranteed to fitwithin the range of a 32-bit signed integer.
You could assume no leading zero bit in theinteger’s binary representation.
Example 1:
Input: 5
Output: 2
Explanation: The binary representation of 5is 101 (no leading zero bits), and its complement is 010. So you need to output2.
Example 2:
Input: 1
Output: 0
Explanation: The binary representation of 1is 1 (no leading zero bits), and its complement is 0. So you need to output 0.
谷歌翻译:给定一个正整数,输出其补数。 补码策略是翻转其二进制表示的比特。
这题也是用的将一个整数变成字符型的二进制数组,然后再将1变成0,0变成1。最后再将二进制数变成十进制输出。代码如下:
public class Solution {
public int findComplement(int num) {
int sum=0;
int s=1;
String bytes =Integer.toBinaryString(num);
char c[]=bytes.toCharArray();
for(inti=0;i<c.length;i++){
if(c[i]=='1'){
c[i]='0';
}else{
c[i]='1';
}
}
for(inti=c.length-1;i>=0;i--){
sum += s * (c[i] == '1' ? 1 : 0);
s*= 2;
}
returnsum;
}
}
- 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)
- 【Hibernate】——多对多映射
- 【Luogu】 食物链
- 使用javadoc工具生成API文档
- STL容器之map
- kubernetes google_containers/pause浅析
- 476. Number Complement
- Best questions about python at stackoverflow in 2016
- Jquery的loading插件
- 移动端H5页面注意事
- Java中读取properties文件的两种方式
- MongoDB中正则的使用(模糊查询)
- CSU-1020
- 策略模式
- (二)AssetBundle的创建