c語言整數轉二進位制顯示及統計1的個數
阿新 • • 發佈:2019-02-16
#include "stdio.h" #include "stdlib.h" #include "string.h" int main(void){ int in_int; printf("請輸入一個整數:"); scanf("%d", &in_int); //printf("輸入的整數:%d\n", c); char buf[100]={0}; int len = 0; int ci = in_int; int times1 = 0; //二進位制串中1的個數 do{ int b = ci & 1; buf[len++] = b + '0'; if(b > 0){ times1++;} ci = ci>>1; }while(ci > 0); int i,len2 = len/2; //printf("c=%d, len=%d, len2=%d, str=%s\n", c,len, len2,buf); //反轉字串 for(i=0; i<len2; i++){ char tc = buf[i]; buf[i] = buf[len-1-i]; buf[len-1-i] = tc; } printf("二進位制串:%s, 1的個數:%d\n", buf, times1); return 0; }