問題描述:
給定一個十進制n,統計從 1 到 n的所有數中含有"1"的個數;
例如n=10;
那麼 1 和 10都含有"1",即此時爲2
要求:
算法的時間複雜度不得超過o(n);
具體方案:
分析:
xxxxx0xxxxx
xxxxx1xxxxx
xxxxx2xxxxx
xxxxx3xxxxx
....
.
.
.
xxxxx9xxxxx
不爲"x"的數即我們要分析的數位,這個數位爲"1"的情況可分爲2部分:
高位相關(不包括該位),: 高位的數值*100000(該位在第六位)
低位相關(不包括該位),又分爲2種情況:1)該位小於1,即爲0 這是這個部分記0處理
2)該位大於等於1,這個部分記爲: 低位數字值再加1
如此從低位到高位逐一考慮累加就會得到"1"的總個數.
具體代碼(vs2005, win32,c++)
unsigned long count(unsigned long n);
int _tmain(int argc, _TCHAR* argv[])
{
printf("%ld/n",count(100));
return 0;
}
unsigned long count(unsigned long n)
{
unsigned long int num=0;
int CurNum;
unsigned long HighNum,LowNum;
//依次有低位到高位考慮1的個數
short int cur;
unsigned long int factor=1;
unsigned long int high;
unsigned long int low;
unsigned long int count=0;
while(n/factor)
{
//取出高位
high=n/(factor*10);
//取出低位
low=n%factor;
//取出當前位
cur=(n/factor)%10;
switch(cur)
{
case 0:
count+=(high*factor);
break;
case 1:
count+=(high*factor);
count+=(low+1);
break;
default:
count+=(high*factor);
count+=factor;
break;
}
factor*=10;
}
return count;
}