[Algorithm-Java implementation] Calculate the number of 1 in the binary corresponding to int

[Algorithm-Java implementation] Calculate the number of 1 in the binary corresponding to int

1. Problem description:

1. Input: Input an integer of type int

2. Output: output this integer int corresponding to the number of 1 in binary

For example: input 14, the corresponding binary number is 1110, then output 3

​ Input 15, the corresponding binary number is 1111, then output 4

2. Question answer:

1. Enter a decimal number of type int and convert it to a binary number (Divide by two), create a String type string s and store the remainder in turn, convert s into a character array, and create a statistical variable count to count the number of 1 in the array.

2. In order to facilitate the printing of this binary number, this question will convert the String string to StringBuffer string sb, and call the reverse() method of sb to print out the binary number

3. The reverse() method realizes string reversal. As for why it is necessary to reverse, please refer toDivide by two

For example: enter 14, the stored in s is 0111, call b.reverse().toString() to print out 1110

3. Algorithm analysis:

Time complexity O(n), additional space complexity O(1)

code show as below

import java.util.*;

public class Solution {
    
    
    /**
     * 计算int对应二进制中1的个数
     * @param n int整型 数字
     * @return int整型
     */
	public static void main(String[] args) {
    
    
		Scanner in=new Scanner(System.in);
		int n=in.nextInt();
		int result=countBit (n);
		System.out.println(result);
		
	}
    public static int countBit (int n) {
    
    
        // write code here
    	String s="";
        //除二取余法
    	while(n>0) {
    
    
    		int a=n%2;
    		n/=2;
    		s+=Integer.valueOf(a);
    	}
    	StringBuffer sb=new StringBuffer(s);
    	String s2=sb.reverse().toString();
        //打印出这个二进制数字
        //System.out.println(s2);  
    	int count=0;//统计变量
    	char[] array=s2.toCharArray();
    	for(int i=0;i<array.length;i++) {
    
    
    		if(array[i]==1);
    		count++;
    	}
    	return count;
    }
}

Guess you like

Origin blog.csdn.net/hkdhkdhkd/article/details/109218698