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:

  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.
解释:

分析:

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
原创粉丝点击