zoukankan      html  css  js  c++  java
  • 第28题:求整数的二进制表示中1的个数

    github:https://github.com/frank-cq/MyTest

    第28题:输入一个整数,求该整数的二进制表达中有多少个1。例如输入10,由于其二进制表示为1010,有两个1,因此输出2。


    代码

    package test028;
    
    /**
     * Created by cq on 2015/6/28.
     * 第28题:输入一个整数,求该整数的二进制表达中有多少个1。例如输入10,
     *        由于其二进制表示为1010,有两个1,因此输出2。
     */
    public class Test028 {
        public static int getNumOfOne(int n){
            if (n < 1){
                return -1;
            }
    
            int count = 0;
            while (n != 0){
                if ((n&1) == 1){
                    count++;
                }
                n >>= 1;
            }
            return count;
        }
    
        public static void main(String[] args){
            System.out.println("11的二进制表示中有 "+getNumOfOne(11)+" 个1。");
        }
    }
    




    执行结果

    Connected to the target VM, address: '127.0.0.1:3174', transport: 'socket'
    Disconnected from the target VM, address: '127.0.0.1:3174', transport: 'socket'
    11的二进制表示中有 31。
    
    Process finished with exit code 0
  • 相关阅读:
    django 如何重用app
    vim常用命令
    linux find grep
    linux su su-的区别
    linux定时任务crontab
    linux shell的单行多行注释
    python字符串的截取,查找
    gdb调试
    python字符转化
    python读写文件
  • 原文地址:https://www.cnblogs.com/read-the-spring-and-autumn-annals-in-night/p/12041967.html
Copyright © 2011-2022 走看看