package domain; // 编写一个函数,求一个数的二进制表示中的1位的个数,例如9的二进制表示为1001,1位的个数为2。 public class CountOne { //设计一个方法 将10进制 转为 2 进制 public static StringBuilder getB(int num){ StringBuilder sb = new StringBuilder(); int orginnum = num; while(num != 0){ int yushu=num%2; // 每次除完之后的余数 sb.append(yushu); num /= 2; // 每次除完之后的商 } sb.reverse(); return sb; } // 设计一个方法 用来统计 StringBuilder 里面的1的个数 public static int getCount(int num){ int count = 0; String res = String.valueOf(CountOne.getB(num)); for (char value : res.toCharArray()){ if (value == '1'){ count++; } } return count; } public static void main(String[] args) { System.out.println(CountOne.getCount(9)); } }
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> int back_bit(int n) { int count = 0;//创建一个计数器。 while (n)//如果n不为零,则证明n中有1,进入循环。 { n = n & (n - 1);//将n(二进制位中)中最右边的一个1去除。 //eg. //n = 3 =>011(前面那些位都是0,对结果影响不大,就省略了。) //n -1 = 2 => 010 //n = n & (n-1) = 010 count++ = 1; //n = 2 =>010 //n - 1 = 1 => 001 //n = n & (n-1) = 000 count++ = 2; count++;//去除之后,计数器加1,证明n(二进制位中)至少有一个1。 //返回判断n是否等于0,不等于0则证明n中还有1(在二进制为中),继续循环。若n为0,则结束循环。 } return count;//返回计数器中的值,即为1(在二进制为中)的个数。 } int main() { int n = 0; scanf("%d", &n); int i = back_bit(n);//计算1的个数的函数,其返回值就是1的个数。 printf("二进位中1的个数是 %d\n", i); return 0; }
#include<iostream> (720)#include<string> #include<algorithm> using namespace std; int main() { int n; cin >> n; //transform to B string str(""); do { str += n % 2+'0'; n = n / 2; } while (n != 0); reverse(str.begin(), str.end()); cout << str; int count=0; for (int i = 0; i < str.size(); ++i) { if (str[i] == '1')count++; } cout << endl << count; return 0; }
package com.ht; import java.util.Scanner; public class Test { public static void main(String[] args) { System.out.println("请输入一个十进制数:"); Scanner reader = new Scanner(System.in); int n = 0; int i = 0; int r = 0; n = reader.nextInt(); int[] a = new int[10]; do { if (n % 2 == 1) { r = 1; } else { r = 0; } a[i] = r; n = n / 2; i++; } while (n > 0); int count = 0; for (int j = i - 1; j >= 0; j--) { if (a[j] == 1) { count++; } } System.out.println(count); }}
public int test(int i) { int length = Integer.toBinaryString(i).split("1").length; System.out.println(length); return length; }