輸入一個整數,輸出該數二進制表示中1的個數。其中負數用補碼錶示

本題本人直接調用函數,因此比較簡單,直接貼代碼

public class Solution {
    public int NumberOf1(int n) {
        String string=Integer.toBinaryString(n);
		int count=0;
		for(int i=0;i<string.length();i++) {
			if(string.charAt(i)=='1') {
				count++;
			}
		}
        return count;
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章