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;
        }
    }
    
    
  • 相关阅读:
    HDU 3572 Task Schedule(拆点+最大流dinic)
    POJ 1236 Network of Schools(Tarjan缩点)
    HDU 3605 Escape(状压+最大流)
    HDU 1166 敌兵布阵(分块)
    Leetcode 223 Rectangle Area
    Leetcode 219 Contains Duplicate II STL
    Leetcode 36 Valid Sudoku
    Leetcode 88 Merge Sorted Array STL
    Leetcode 160 Intersection of Two Linked Lists 单向链表
    Leetcode 111 Minimum Depth of Binary Tree 二叉树
  • 原文地址:https://www.cnblogs.com/wupeixuan/p/8623150.html
Copyright © 2011-2022 走看看