1. 程式人生 > 其它 >每日演算法之整數中1出現的次數(從1到n整數中1出現的次數)

每日演算法之整數中1出現的次數(從1到n整數中1出現的次數)

JZ43 整數中1出現的次數(從1到n整數中1出現的次數)

描述

輸入一個整數 n ,求 1~n 這 n 個整數的十進位制表示中 1 出現的次數
例如, 1~13 中包含 1 的數字有 1 、 10 、 11 、 12 、 13 因此共出現 6 次

思路:暴力統計法

遍歷1到n的每個數字,然後對每個數字單獨遍歷它的每一位,檢查是否是1,如果是1則計數。
具體做法:
step 1:從1遍歷到n,檢視每一個數字。
step 2:對於每個數字,用連除法每次判斷最後一位數字是否為1,並進行計數。

程式碼

package mid.JZ43整數中1出現的次數;

public class Solution {
    public int NumberOf1Between1AndN_Solution(int n) {
        int res = 0;
        for (int i = 1; i <= n; i++) {
            for (int j = i; j > 0; j = j / 10) {
                if (j % 10 == 1) {
                    res++;
                }
            }
        }
        return res;
    }

    public static void main(String[] args) {
        System.out.println(new Solution().NumberOf1Between1AndN_Solution(13));
    }
}