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;

    }

}

0 0
原创粉丝点击