zoukankan      html  css  js  c++  java
  • 剑指Offer-二进制中1的个数

    题目描述

    输入一个整数,输出该数二进制表示中1的个数。其中负数用补码表示。

    思路

    思路一:

    用flag来与n的每位做位于运算,来判断1的个数

    思路二:

    如果一个整数不为0,那么这个整数至少有一位是1。

    如果我们把这个整数减1,那么原来处在整数最右边的1就会变为0,原来在1后面的所有的0都会变成1(如果最右边的1后面还有0的话)。

    其余所有位将不会受到影响。

    思路三:

    用Integer.bitCount函数统计参数n转成2进制后有多少个1

        public static int bitCount(int i) {
            // HD, Figure 5-2
            i = i - ((i >>> 1) & 0x55555555);
            i = (i & 0x33333333) + ((i >>> 2) & 0x33333333);
            i = (i + (i >>> 4)) & 0x0f0f0f0f;
            i = i + (i >>> 8);
            i = i + (i >>> 16);
            return i & 0x3f;
        }
    

    代码实现

    package Other;
    
    /**
     * 二进制中1的个数
     * 输入一个整数,输出该数二进制表示中1的个数。其中负数用补码表示。
     */
    public class Solution19 {
        public static void main(String[] args) {
            Solution19 solution19 = new Solution19();
            System.out.println(solution19.NumberOf1_3(3));
        }
    
        /**
         * 用Integer.bitCount函数统计参数n转成2进制后有多少个1
         *
         * @param n
         * @return
         */
        public int NumberOf1_3(int n) {
            return Integer.bitCount(n);
        }
    
        /**
         * 如果一个整数不为0,那么这个整数至少有一位是1。
         * 如果我们把这个整数减1,那么原来处在整数最右边的1就会变为0,原来在1后面的所有的0都会变成1(如果最右边的1后面还有0的话)。
         * 其余所有位将不会受到影响。
         *
         * @param n
         * @return
         */
        public int NumberOf1_2(int n) {
            int count = 0;
            while (n != 0) {
                count++;
                n = (n - 1) & n;
            }
            return count;
        }
    
        /**
         * 用flag来与n的每位做位于运算,来判断1的个数
         *
         * @param n
         * @return
         */
        public int NumberOf1(int n) {
            int count = 0;
            int flag = 1;
            while (flag != 0) {
                if ((flag & n) != 0) {
                    count++;
                }
                flag = flag << 1;
            }
            return count;
        }
    }
    
    
  • 相关阅读:
    关于document.body.scrollTop用法
    set回顾
    用户登录与注册
    编写通讯录2
    利用字典的特性编写一个通讯录
    shelve模块
    shutil模块
    列表的拓展
    随机生成验证码2
    递归与欧几里得算法结合求最大公约数
  • 原文地址:https://www.cnblogs.com/wupeixuan/p/8623150.html
Copyright © 2011-2022 走看看