從1到n的整數中1出現的次數

來源:互聯網
上載者:User

在<編程之美>和<劍指offer>上都有這麼一道題目,那就是求從1到n的整數中1出現的次數。

這兩本書中都給出了兩種演算法,本人覺得<編程之美>上的演算法更勝一籌。現將兩種演算法實現如下。

方法1:

一個直觀的方法就是遍曆從1到n的每一個整數,利用一個子函數求出一個整數中所含1的個數,然後將所有整數中包含1的次數相加得到最後的結果。

C代碼實現:

#include <stdio.h>unsigned int totalnumberofone(unsigned int n);unsigned int numberofone(unsigned int n);int main(){    printf("%d",totalnumberofone(12));    return 0;}unsigned int totalnumberofone(unsigned int n){    unsigned int count=0;    while(n>0)    {        count+=numberofone(n--);    }    return count;}unsigned int numberofone(unsigned int n){    unsigned int count=0;    while(n!=0)    {        if(n%10==1)        {            ++count;        }        n=n/10;    }    return count;}

方法2:

利用上面的方法1在n較小的情況下時間消耗還是不大的,但是如果n很大,那麼利用上面的方法時間消耗可就很大了,時間複雜度應該為線性對數級的。我們能不能想到一個更快的辦法呢?或者我們的方法能不能不跟n的大小有關,而只跟n的位元有關呢?

我們只需簡單的分析就可以知道,1出現的次數無非只可能出現在n整數的不同進位上,從最高位到最低位都有可能出現。我們只需分析1出現在每個位上出現的次數,然後將所有的次數相加就可以得到最終1出現的次數,而這種演算法的時間複雜度只跟數字n的位元有關,即屬於對數層級的。

C實現:

unsigned int totalnumofone(unsigned int n){    unsigned int count=0;    unsigned int highnum,lownum,curnum;    unsigned int factor=1;    while(n/factor!=0)    {        highnum=n/(factor*10);        curnum=(n/factor)%10;        lownum=n-(n/factor)*factor;        switch(curnum)        {            case 0:            count+=highnum*factor;            break;            case 1:            count+=highnum*factor+lownum+1;            break;            default:            count+=(highnum+1)*factor;        }        factor*=10;    }    return count;}

上述程式中的factor值得是當前的進位,1表示個位,10表示十位,100表示百位.......curnum表示當前位上的數字,highnum和lownum分別表示當前位前的數字和當前位後的數字。如有不懂,可參考編程之美2.4。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.