Leetcode 233 Number of Digit One,leetcodedigit

來源:互聯網
上載者:User

Leetcode 233 Number of Digit One,leetcodedigit
1. 問題描述

  給定一個整數n,在所有不大於n的非負整數中,計算包含數字1的整數的個數。例如n=13的結果為6,包含1的數字有1,10,11,12,13。

2. 方法與思路

  這個問題最直觀的方法就是累加1到n所有的包含1的數的個數。每個數通過迴圈取餘10的方法判斷是否包含1。但是這種思路效率並不高,數字n有logn位,總得時間複雜度為O(nlogn)。
  利用數位規律,簡化計算。以數字21567為例。先將數字分為兩段:“1到1567”和“1568到21567”。
  從1568到21567這段,分為兩種情況,1出現在最高位的情況。從10000到19999的數字中,包含1的一共出現了104個,但對於數字12345,1出現在10000到12345的萬位的個數就是2345+1=2346次。再看1出現在從1568到21567後4位的情況。同樣分成兩段,1568到11568和11569到21568,每一段剩下的4位書中,設其中一位是1,其他三位可以是0~9之間的數,根據排列組合原理處理即可。
  至於從1到1567利用遞迴就可以了。
  

class Solution {private:    int numofOne(int n)    {        if(n == 0) return 0;        if(n > 0 && n < 10) return 1;        int a = n,cnt = 0,num1,num2,num3;        while(a/10)        {            a /=10;            cnt++;        }        if(a > 1)            num1 = pow(10,cnt);        else if(a == 1)            num1 = n%(int)pow(10,cnt)+1;        num2 = a * (cnt)*pow(10,cnt-1);        num3 = numofOne(n%(int)pow(10,cnt));        return num1+num2+num3;    }public:    int countDigitOne(int n) {        return numofOne(n);    }};

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

聯繫我們

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