Huawei online programming question series-15-find the number of int positive integers when they are stored in memory

Problem Description:

1. The problem involves knowledge points

  • byte data statistics
  • Logical operators

2. Solve by yourself

  • First, convert the original data into the form of 01. (each time take the power value of 2 closest to him, and then assign 1 to the flag bit.)
  • After conversion, it is compiled into the number of 1 in the array
package com.chaoxiong.niuke.huawei;
import java.util.Scanner;
/**
 * Create by tianchaoxiong on 18-4-10.
 */
public class HuaWei_15 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int key = scanner.nextInt();
        System.out.println(geResult(key));
    }

    private static int geResult(int key) {
        // keyArr is used to store the value represented by each position
        int[] keyArr = new int[32];
        // indexArr is the flag bit. Save the converted 0 1 form
        int[] indexArr = new int[32];
        //Assign values to flag digit groups and keyArr
        for (int i = 0; i < 32; i++) {
            keyArr[i] = (int) Math.pow(2, i);
            indexArr[i] = 0;
        }
        while (key > 0) {
            // Take the nearest power of 2 smaller than key
            int lateMaxKey = getLateMaxKey(keyArr, indexArr, key);
            key = key - lateMaxKey;
        }
        // Count the number of occurrence 1
        return getNum(indexArr);
    }

    private static int getNum(int[] indexArr) {
        int num = 0;
        for (int each : indexArr) {
            if (each == 1)
                num++;
        }
        return num;
    }

    private static int getLateMaxKey(int[] keyArr, int[] indexArr, int key) {
        for (int i = 0; i < keyArr.length; i++) {
            if (key < keyArr[i]) {
                indexArr[i - 1] = 1;
                return keyArr[i - 1];
            }
        }
        return 0;
    }
}

3. High quality answer

  • N = n & (n-1) algorithm
package com.chaoxiong.niuke.huawei;
import java.util.Scanner;
/**
 * Create by tianchaoxiong on 18-4-10.
 */
public class HuaWei_15_2 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int key = scanner.nextInt();
        System.out.println(count1(key));
    }
    private static int count1(int n) {
        int count=0;
        while(n!=0){//Integer is not 0, there must be 1
            ++count;
            n=n&(n-1);
        }
        return count;
    }
}

4. Summary of this question

How to convert an integer to a binary sequence:
1: Using the flag bit, find the largest power number smaller than him each time, and meet each other iteratively
2: No saving, only statistics. N = n & (n-1) algorithm is used

Tags: Java

Posted on Thu, 19 Mar 2020 12:28:40 -0400 by nicx