Given an integer n, count the total number of digit 1 appearing in all non-negative integers less than or equal to n.
給出一個整數n,計算在所有小于或等于n的非負整數中,數字1出現的個數。
這里最麻煩的自然就是當數字大的時候,用簡單的循環暴力計數肯定會超時,這個時候考驗的就是找規律的能力了
For example:
Given n = 13,
Return 6, because digit 1 occurred in the following numbers: 1, 10, 11, 12, 13.
My Solution
(Java) Version 1 Time: Time Limit Exceeded:
這里先記錄一個單純的可愛的直觀的暴力解法,當然這個肯定是會超時的,記錄一下以作對比。對每一個數轉化為string的字符數組然后一個個數,沒錯,赤果果地超時了,超時的輸入是824883294,eclipse也花了我切換幾次網頁的時間才跑出結果
public class Solution {
public int countDigitOne(int n) {
int count = 0;
for (int i = 0; i <= n; i++) {
String s = String.valueOf(i);
for (char c : s.toCharArray()) {
if (c == '1') {
count++;
}
}
}
return count;
}
}