日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程资源 > 编程问答 >内容正文

编程问答

233. Number of Digit One

發(fā)布時(shí)間:2024/4/13 编程问答 23 豆豆
生活随笔 收集整理的這篇文章主要介紹了 233. Number of Digit One 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

題目:

Given an integer n, count the total number of digit 1 appearing in all non-negative integers less than or equal to n.

For example:
Given n = 13,
Return 6, because digit 1 occurred in the following numbers: 1, 10, 11, 12, 13.

鏈接:?http://leetcode.com/problems/number-of-digit-one/

題解:

又是數(shù)學(xué)題,主要思路是用遞歸來(lái)做。還有一些別的解法,二刷的時(shí)候爭(zhēng)取理解最優(yōu)解。

下面我們來(lái)一步步分析:

  • n < 1時(shí),結(jié)果為0
  • 1 <= n < 10時(shí),結(jié)果為1 假定n = 312,我們把這個(gè)計(jì)算過(guò)程分解為幾個(gè)步驟:
  • (1 ~ 99), 結(jié)果為 countDigitOne(99)
  • (100 ~ 199), 結(jié)果為 100 + countDigitOne(99)
  • (200 ~ 299), 結(jié)果為countDigitOne(99)
  • (300 ~ 312), 結(jié)果為countDigitOne(12)
  • 假定n = 112, 我們也把這個(gè)計(jì)算過(guò)程分解一下:
  • (1 ~ 99), 結(jié)果為?countDigitOne(99)
  • (100 ~ 112), 結(jié)果為 112 - 100 + 1 + countDigitOne(12)
  • 由此我們可以推出通項(xiàng)公式
  • Time Complexity ?- O(log10n), Space Complexity - O(log10n)

    public class Solution {public int countDigitOne(int n) {if (n < 1)return 0;if (n < 10)return 1;int baseInTen = (int)Math.pow(10, String.valueOf(n).length() - 1); int highestDigit = n / baseInTen; // get the highest digit of nif(highestDigit == 1)return countDigitOne(baseInTen - 1) + (n - baseInTen + 1) + countDigitOne(n % baseInTen);elsereturn highestDigit * countDigitOne(baseInTen - 1) + baseInTen + countDigitOne(n % baseInTen);} }

    ?

    Reference:

    https://leetcode.com/discuss/44281/4-lines-o-log-n-c-java-python

    https://leetcode.com/discuss/44279/clean-c-code-of-log10-complexity-with-detailed-explanation

    https://leetcode.com/discuss/44314/accepted-solution-using-counting-principle-with-explanation

    https://leetcode.com/discuss/44465/my-ac-java-solution-with-explanation

    https://leetcode.com/discuss/44617/my-recursion-implementation

    https://leetcode.com/discuss/47774/0ms-recursive-solution-in-c-8-line-code

    https://leetcode.com/discuss/46366/ac-short-java-solution

    https://leetcode.com/discuss/64604/my-simple-and-understandable-java-solution

    https://leetcode.com/discuss/64962/java-python-one-pass-solution-easy-to-understand

    https://leetcode.com/discuss/54107/0-ms-recursive-solution

    https://leetcode.com/discuss/58868/easy-understand-java-solution-with-detailed-explaination

    總結(jié)

    以上是生活随笔為你收集整理的233. Number of Digit One的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

    如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。