深感自己的邏輯思維略差,知識(shí)面略窄,于是最近開始著手練習(xí)刷nowcoder,提升一下自己。
首先挑一個(gè)通過(guò)率高的算法題試試,題目是 “ 輸入一個(gè)int型的正整數(shù),計(jì)算出該int型數(shù)據(jù)在內(nèi)存中存儲(chǔ)時(shí)1的個(gè)數(shù)?”。嗯,首先想到的是對(duì)2取余,計(jì)數(shù)++, 然后沒(méi)有通過(guò),焦灼...
經(jīng)查閱,java有一個(gè)厲害的方法,Integer.toBinaryString(19934318); 這個(gè)方法可以直接將一個(gè)int對(duì)應(yīng)的二進(jìn)制數(shù),然后,你可以遍歷該方法返回的二進(jìn)制String.
完整代碼如下:
import java.util.Scanner;
public class Main{
? ? public static void main(String args[]){
? ? ? ? int n=0;
? ? ? ? Scanner sc = new Scanner(System.in);
? ? ? ? while(sc.hasNextInt()){
? ? ? ? ? ? int num = sc.nextInt();
? ? ? ? ? ? String str=Integer.toBinaryString(num);
? ? ? ? ? ? for (int i = 0; i < str.length(); i++) {
? ? ? ? ? ? if ('1'? ==str.charAt(i)) {
? ? ? ? ? ? ? ? n++;
? ? ? ? ? ? }else {
? ? ? ? ? ? ? ? continue;
? ? ? ? ? ? }
? ? ? ? }
? ? ? ? }
? ? ? ? System.out.println(n);
? ? }
}