1. 程式人生 > >[Lintcode學習筆記 ](3. Digit Counts)

[Lintcode學習筆記 ](3. Digit Counts)

題目 “Digit Counts”

Count the number of k’s between 0 and n. k can be 0 - 9.(計算出一組數中包含k的個數,同一個數裡多次出現k要多次計數) Example if n = 12, k = 1 in [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] we have FIVE 1’s (1, 10, 11, 12)

題目詳解

思路:輸入一個數據,依次對資料的每一位進行判斷,看是否等於k

原始碼:

// An highlighted block
class Solution {
public:
    /**
     * @param k: An integer
     * @param n: An integer
     * @return: An integer denote the count of digit k in 1..n
     */
int digitCounts(int k, int n) { // write your code here int j=0; int bit_right; int num_k=0; if(k==0) { num_k++; } for(int i=0;i<=n;i++) { j=i; while(j) //j=0時一個數中k的個數計算結束 {
bit_right=j%10; //取該數的個位數(對10求餘) j/=10; //對該數除以10並取整 if(bit_right==k) { num_k++; // break; } } } return num_k; } };