leetcode 476. Number Complement
来源:互联网 发布:java gc回收机制 编辑:程序博客网 时间:2024/06/17 02:21
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.
我的解法:
public class Number_Complement_476 {public int findComplement(int num) {int result=0;int pos=0;while(num>=1){int yu=num%2;int bit=(yu==1?0:1);result+=bit*Math.pow(2, pos);pos++;num=num/2;}return result;}public static void main(String[] args) {// TODO Auto-generated method stubNumber_Complement_476 n = new Number_Complement_476();System.out.println(n.findComplement(5));System.out.println(n.findComplement(1));}}然后我发现大神的解法:100110, its complement is 011001, the sum is 111111. So we only need get the min number large or equal to num, then do substraction.
public int findComplement(int num) { int i = 0; int j = 0; while (i < num) { i += Math.pow(2, j); j++; } return i - num; }Same idea, but using bit manipulation instead of Math.pow().
public class Solution { public int findComplement(int num) { int n = 0; while (n < num) { n = (n << 1) | 1; } return n - num; }}
0 0
- LeetCode 476. Number Complement
- leetcode 476. Number Complement
- 【Leetcode】476. Number Complement
- 【Leetcode】476. Number Complement
- LeetCode 476. Number Complement
- LeetCode 476. Number Complement
- LeetCode--476. Number Complement
- LeetCode 476. Number Complement
- 476. Number Complement [LeetCode]
- [LeetCode]476.Number Complement
- 【LeetCode】 476. Number Complement
- LeetCode 476. Number Complement
- LeetCode 476. Number Complement
- 【LeetCode】476. Number Complement
- leetcode 476. Number Complement
- [LeetCode]476. Number Complement
- LeetCode 476. Number Complement
- 【LeetCode】476. Number Complement
- ReactiveCocoa 中 RACSignal 是如何发送信号的
- 欢迎使用CSDN-markdown编辑器
- 欢迎使用CSDN-markdown编辑器
- 初探React-router实现导航
- 分布式大数据多维分析(OLAP)引擎Apache Kylin安装配置及使用示例
- leetcode 476. Number Complement
- struct tm 赋值设置时间
- Ubuntu16+Eclipse+OpenCV+CUDA
- Arrays.asList()
- 关系型数据库的范式分析并举例
- 最小路径和
- text/html和text/plain的区别
- 错误处理:java.lang.NoSuchMethodException: org.apache.catalina.deploy.WebXml addFilter
- 深度学习-DataPreprocessing