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:

  1. The given integer is guaranteed to fit within the range of a 32-bit signed integer.
  2. 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
原创粉丝点击