zoukankan      html  css  js  c++  java
  • 二进制中1的个数 10

    三种方法

       

    第一种不断除2

       

    2可以用右移方式,但这种方式对于负数的话容易造成左边全为1,进入死循环

       

    可以判断如果输入负数的话,取他的相反数,也就是取绝对值

       

    第二种方法不断乘2,然后用n与该乘2的数做与,如果不为零,则说明该位有一个1

       

    但这种方式这个不断乘2的数字要乘到溢出才完,可以设定while循环条件location乘以2小于n

       

    第三种方法利用求最右边的1,也就是求一个数是否是2k次方

       

    如果n&(n-1)等于1的话,说明n2k次方

       

    package numOf1InBinary10;

       

    public class NumOf1InBinary10 {

    static int sol1(int n) {

    int count = 0;

       

    while (n != 0) {

    if (n % 2 == 1) {

    count++;

    }

    n = n >> 1;

    }

    return count;

    }

    static int sol2(int n){

    int count=0;

    int location=1;

    while (location!=0) {

    if ((n&location)!=0) {

    count++;

    }

    location=location<<1;

    }

    return count;

       

    }

    static int sol3(int n){

    int count=0;

    while (n!=0) {

    count++;

    n=n&(n-1);

    }

    return count;

       

       

    }

    public static void main(String[] args) {

    // TODO Auto-generated method stub

    System.out.println(sol3(0));

    //                System.out.println((7&2));

    }

       

    }

  • 相关阅读:
    HDU 4512 吉哥系列故事——完美队形I (LCIS)
    HDU 4506 小明系列故事——师兄帮帮忙
    SDUT Greatest Number
    HDU 4545 魔法串
    HDU 4546 比赛难度 (优先队列 * * )
    Android布局学习
    K9mail编译
    没有小的项目
    dxDBTreeView自动删除数据问题
    SQL Server查看表空间占用情况
  • 原文地址:https://www.cnblogs.com/keedor/p/4381145.html
Copyright © 2011-2022 走看看