編程之美 2.4 1的數目,編程之美2.4數目

來源:互聯網
上載者:User

編程之美 2.4 1的數目,編程之美2.4數目

      這道題的意思是,給定一個數n,那麼從1到n這n個數中,1出現了幾次。這個問題開始看,肯定不容易做,往往都是利用最笨的方法,一個數一個數的找就行了,那麼如果n很大,就需要非常多的時間了,書中提供了更好的方法,需要發現數字中存在的相關規律:

對於數abcde,c這位出現1的次數分以下情況:1.若c > 1,結論是(ab + 1)* 100;2.若c == 1,結論是(ab)* 100 + de + 1;3.若c < 1,結輪是 ab * 100 + de + 1;

      上面的意思就是,對於每一位出現1的情況都和它的高位和低位是相關的,所以,我們只要擷取當前位,高位,低位就可以了,所以,首先,給出函數定義:

/*2.4 1的數目*/int DutCountOf1InN(int);

      之後,我們利用上面的公式很容易寫出如下簡單的代碼:

/* * 對於數abcde,c這位出現1的次數分以下情況: * 1.若c > 1,結論是(ab + 1)* 100; * 2.若c == 1,結論是(ab)* 100 + de + 1; * 3.若c < 1,結輪是 ab * 100 + de + 1;*/int DutCountOf1InN(int n){if (n <= 0)return 0;int count = 0;/*乘數因子,以10倍遞增*/int factor = 1;int lowerNum = 0;int currNum = 0;int highNum = 0;while (n / factor != 0){/*低位元字*/lowerNum = n - (n / factor) * factor;/*當前位元字*/currNum = (n / factor) % 10;/*高位元字*/highNum = n / (factor * 10);switch (currNum){case 0:count += highNum * factor;break;case 1:count += highNum * factor + lowerNum + 1;break;default:count += (highNum + 1) * factor;break;}factor *= 10;}return count;}

      這個問題到這裡還沒有結束,假如,題目問的不是1的個數,而是2,3.。。。的個數呢,還是一樣的解決辦法嗎?經過分析,我們發現,依然是利用上面的那個公式就可以了,所以,利用下面的代碼可以得到c的個數,當然c是屬於[1,9]:

      函式宣告

/*c的數目*/int DutCountOfCInN(int, int);


      原始碼:

/* *對於數abmde,m這位出現c的次數分以下情況: * 1.若m > c,結論是(ab + 1)* 100; * 2.若m == c,結論是(ab)* 100 + de + 1; * 3.若m < c,結輪是 ab * 100 + de + 1;*/int DutCountOfCInN(int N, int c){if (N <= 0)return 0;int sum = 0;    int low = 0, cur = 0, high = 0;    int ifactor = 1;    while (N / ifactor != 0)    {        low = N - (N / ifactor) * ifactor;        cur = (N / ifactor) % 10;        high = (N / ifactor) / 10;        if (cur < c)        {            sum += high * ifactor;        }        else if (cur == c)        {            sum += high * ifactor + low + 1;        }        else        {            sum += (high + 1) * ifactor;        }        ifactor *= 10;    }    return sum;}





124711……這樣下去,第25個數是?

1=1+0
2=1+1
4=1+1+2
7=1+1+2+3
11=1+1+2+3+4
……
an=1+[1+2+……+(n-1)]=1+n(n-1)/2
a25=1+25*24/2=301
 
18與24的比例是哪個




 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.