在從 1 到 n 的正數中 1 出現的次數
題目:
輸入一個整數 n,求從 1 到 n 這 n 個整數的十進制表示中 1 出現的次數。
例如輸入 12,從 1 到 12 這些整數中包含 1 的數字有 1, 10, 1 1 和 12, 1 一共出現了 5 次
代碼實現(GCC編譯通過):
#include "stdio.h"#include "stdlib.h" int count1(int n);int count2(int n); int main(void){ int x; printf("輸入一個數:"); scanf("%d",&x); printf("/n從0到%d一共遇到%d(%d)個1/n",x,count1(x),count2(x)); return 0;} //解法一int count1(int n){ int count = 0; int i,t; //遍歷1到n for(i=1;i<=n;i++) { t=i; //依次處理當前遍歷到的數字的各個位 while(t != 0) { //若為1則統計加一 count += (t%10 == 1)?1:0; t/=10; } } return count;} //解法二:int count2(int n){ int count = 0;//統計變量 int factor = 1;//分解因子 int lower = 0;//當前處理位的所有低位 int higher = 0;//當前處理位的所有高位 int curr =0;//當前處理位 while(n/factor != 0) { lower = n - n/factor*factor;//求得低位 curr = (n/factor)%10;//求當前位 higher = n/(factor*10);//求高位 switch(curr) { case 0: count += higher * factor; break; case 1: count += higher * factor + lower + 1; break; default: count += (higher+1)*factor; } factor *= 10; } return count;}
分析:
方法一就是從1開始遍歷到N,將其中的每一個數中含有“1”的個數加起來,比較好想。
方法二比較有意思,核心思路是這樣的:統計每一位上可能出現1的次數。
比如123:
個位出現1的數字:1,11,13,21,31,...,91,101,111,121
十位出現1的數字:10~19,110~119
百位出現1的數字:100~123
總結其中每位上1出現的規律即可得到方法二。其時間復雜度為O(Len),Len為數字長度
整數的二進制表示中 1 的個數
題目:整數的二進制表示中 1 的個數
要求:
輸入一個整數,求該整數的二進制表達中有多少個 1。
例如輸入 10,由于其二進制表示為 1010,有兩個 1,因此輸出 2。
分析:
解法一是普通處理方式,通過除二余二統計1的個數;
解法二與解法一類似,通過向右位移依次處理,每次與1按位與統計1的個數
解法三比較奇妙,每次將數字的最后一位處理成0,統計處理的次數,進而統計1的個數
代碼實現(GCC編譯通過):
#include "stdio.h"#include "stdlib.h" int count1(int x);int count2(int x);int count3(int x); int main(void){ int x; printf("輸入一個數:/n"); setbuf(stdin,NULL); scanf("%d",&x); printf("%d轉二進制中1的個數是:",x); printf("/n解法一:%d",count1(x)); printf("/n解法二:%d",count2(x)); printf("/n解法三:%d",count3(x)); printf("/n"); return 0;} //除二、余二依次統計每位int count1(int x){ int c=0; while(x) { if(x%2==1) c++; x/=2; } return c;} //向右移位,與1按位與統計每位int count2(int x){ int c=0; while(x) { c+=x & 0x1; x>>=1; } return c;} //每次將最后一個1處理成0,統計處理次數int count3(int x){ int c=0; while(x) { x&=(x-1); c++; } return c;}
新聞熱點
疑難解答
圖片精選