1. 程式人生 > >牛客網——華為機試(題15:求int型正整數在記憶體中儲存時1的個數)(Java)

牛客網——華為機試(題15:求int型正整數在記憶體中儲存時1的個數)(Java)

題目描述:

輸入一個int型的正整數,計算出該int型資料在記憶體中儲存時1的個數。

輸入描述:

輸入一個整數(int型別)

輸出描述:

 這個數轉換成2進位制後,輸出1的個數

示例1:

輸入:

5

輸出:

2

程式碼: 

import java.util.Scanner;
public class Main {
	public static void main ( String[] args ) {
		Scanner in = new Scanner( System.in );
		int n = in.nextInt();
		int sum = 0;
		while( n != 0 ) {
			if ( n % 2 == 1) {
				sum += 1;
				n = n / 2;
			}
			else {
				n = n / 2;
			}
		}
		System.out.println( sum );
		in.close();
	}
}