统计二进制数中的1的个数

整数在计算机中使用二进制的形式表示,如整数7用二进制表示为:111,其中1的个数为3。

输入

输入一个整数

输出

输出该整数用二进制表示时,其中1的个数

样例输入

7

样例输出

3
#include <iostream>
using namespace std;
int main()
{
    int a,count = 0;
    cin >> a;
    while(a != 0)
    {
        if(a % 2 == 1)
        {
            count++;
        }
        a = a / 2;
    }
    cout << count << endl;
    return 0;
}

原文地址:https://www.cnblogs.com/Lazy-Cat/p/9838431.html

时间: 2024-08-08 08:42:58

统计二进制数中的1的个数的相关文章

统计二进制数中的1的个数(0277)

程序设计C 实验二 题目五 统计二进制数中的1的个数(0277) 整数在计算机中使用二进制的形式表示,如整数7用二进制表示为:111,其中1的个数为3. 输入一个整数:7 输出该整数用二进制表示时,其中1的个数:3 代码: #include<iostream> #include<math.h> using namespace std; int max(int a, int b) { return a > b ? a : b; } int min(int a, int b) {

&lt;swustoj&gt;?id=277 统计二进制数中的1的个数

链接http://acm.swust.edu.cn/problem/277/ #include <stdio.h> int main() { int sum,num; num=0; scanf("%d",&sum); while(sum) { if(sum%2==1) { num++; } sum/=2; } printf("%d\n",num); return 0; }

统计字符串中每个字符的个数

1 <!DOCTYPE html> 2 <html> 3 <head lang="en"> 4 <meta charset="UTF-8"> 5 <title>统计字符串中每个字符的个数@</title> 6 </head> 7 <body> 8 </body> 9 10 <script type="text/javascript"&

转载:js实现统计字符串中特定字符出现个数的方法

//js统计字符串中包含的特定字符个数 function getPlaceholderCount(strSource) {   //统计字符串中包含{}或{xxXX}的个数   var thisCount = 0;   strSource.replace(/\{[xX]+\}|\{\}/g, function (m, i) {     //m为找到的{xx}元素.i为索引     thisCount++;   });   return thisCount; }

一个非常有用的算法---统计二进制数中1的个数

本人算法小菜,看见一个非常好的算法,统计一个数的二进制数的1的个数.觉得不错,与大家分享. 1 int fun(int x){ 2 int count = 0; 3 while(x){ 4 count++; 5 x = x &(x-1) 6 } 7 return count; 8 } 下面是个人的一点解释(欢迎拍砖) 比如一个数x的二进制后面几位是1000. x-1的二进制后面几位变成了     0111. 二者&,变成了                            0000.

统计二进制数中1的个数

方法1: int CountNumOf1(int digital) { int num = 0; while(digital) { if(digital % 2 == 1) { num ++; } digital /= 2; } return num; } 方法2: int CountNumOf1(int digital) { int num = 0; while(digital) { num += (digital % 2) ? 1: 0; digital /= 2; } return num

c 统计字符串中字符出现的个数

1.单纯用数组来解题 思路:从左往右循环,每次碰到一个字符就和左边的字符串比较,如果有相同的就右移,如果没有找到相同的就从这个位置向右统计个数并输出. 1 #include<stdio.h> 2 3 void calCount(char arr[]) 4 { 5 int i,j,count,had; 6 i = j = count = had = 0; 7 while(arr[i] != '\0') 8 { 9 count = 0; 10 had = 0; 11 for(j=0; j<i

统计字符串中指定字符的个数

输入一个字符串和一个字符,统计这个字符在字符串中出现的次数 输入格式: 输入2行.第1行是字符串,第2行是要查找的字符. 输出格式: 字符出现的次数 输入样例: abcdefgabcdefg a 输出样例: 2 a=input() b=input() def CountAa(s): return s.lower().count(b) if __name__ == "__main__": s = a print(CountAa(s)) 原文地址:https://www.cnblogs.c

统计字符串中重复的字符个数及字符

做华为的试题,发现有很多需要字符串重复相关知识的.现在补上: #include <stdio.h> #include <stdlib.h> #include <string> #include <string.h> #include <iostream> #include <vector> #include <algorithm> using namespace std; int main(int argc, char**