Huawei Online Programming Question Series-15- Find the number of 1s when a positive integer of int type is stored in memory

Problem Description:
Problem Description

1. The question involves knowledge points.

  • Byte data statistics.
  • Logical Operators.

2. Solve it yourself.

  • First convert the original data into the form of 01. (Every time take the value of the power of 2 that is closest to him, and then assign 1 to the flag bit)
  • After conversion, it is compiled into the number of 1s in the array.
package com.chaoxiong.niuke.huawei;
import com.chaoxiong.utils.Utils;

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 用来存每个位置代表的值
        int[] keyArr = new int[32];
        // indexArr 为标志位.存转换好的0 1形式.
        int[] indexArr = new int[32];
        //对标志位数组和keyArr赋值.
        for (int i = 0; i < 32; i++) {
            keyArr[i] = (int) Math.pow(2, 32-1-i);
        }
        System.out.println("处理的数据是: "+key);
//        Utils.printIntArr1(keyArr,keyArr.length);
//        Utils.printIntArr1(indexArr,indexArr.length);
        while (key > 0) {
            int lateMaxKey = getLateMaxKey(keyArr, indexArr, key);
            key = key - lateMaxKey;
        }
//        Utils.printIntArr1(indexArr,indexArr.length);
        // 统计出现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;
                return keyArr[i];
            }
        }
        return 0;
    }
}

3. Quality answers.

  • 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){//整数不为0,必有1
            ++count;
            n=n&(n-1);
        }
        return count;
    }
}

4. Summary of this question.

The method of converting an integer into a binary sequence:
1: Use the flag bit, find the largest power smaller than him each time, and meet it iteratively.
2: Do not save, only count. Use the n=n&(n-1)algorithm.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325967128&siteId=291194637