題目描述
輸入一個整數(shù),輸出該數(shù)32位二進制表示中1的個數(shù)。其中負數(shù)用補碼表示。
思路:
首先將整數(shù)n使用Integer.toBinaryString()函數(shù)轉(zhuǎn)換為二進制字符串,然后將這個字符串使用split()函數(shù)轉(zhuǎn)化那位數(shù)組,再遍歷整個數(shù)組計算其中·1的個數(shù)。
源代碼:
public class Solution
{
? ? public int NumberOf1(int n)
? ? {
? ? ? int count=0;
? ? ? String str= Integer.toBinaryString(n);
? ? ? String [] str1=str.split("");
? ? ? for(int i=0;i<str1.length;i++)
? ? ? {
? ? ? ? if(str1[i].equals("1"))
? ? ? ? {
? ? ? ? ? ? count++;
? ? ? ? }
? ? ? }
? ? ? ? return count;
? ? }
}