笔试系列--美图秀秀(2017年秋招) 整数二进制数的不同位数

来源:互联网 发布:阿里云客服怎么工作 编辑:程序博客网 时间:2024/06/09 18:27

有两个int型(32位)的正整数,返回这两个数对应的二进制的数的位数不同的个数,即15 1111    8 1000  返回 3。

        思路:每次比最后一位,然后向右移位即可,其中比最后一位有一个小技巧,就是数字和1做&运算,即得到最后一位。

        代码:

public class Diff{public static void main(String[] args){Scanner sc = new Scanner(System.in);int a = sc.nextInt();int b = sc.nextInt();System.out.println(Count(a,b));}private static int Count(int a,int b){int count = 0;int len = 32;while(len--!=0){//与运算if(((a&1)^(b&1))==1){count++;}//移位a>>=1;b>>=1;}return count;}}



原创粉丝点击