码迷,mamicode.com
首页 > 其他好文 > 详细

[Algorithm] 3. Digit Counts

时间:2018-11-06 16:48:06      阅读:217      评论:0      收藏:0      [点我收藏+]

标签:nes   code   one   ++   des   col   esc   cti   lse   

Description

Count the number of k‘s between 0 and nk can be 0 - 9.

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)

Answer


    /**
     * @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) {
        // Check every digit from 0 to n.
        int count, temp, i = 0;
        for ( i=0; i<=n; i++ )
        {
            temp = i;
            do
            {
                // Check the ones and tens place respectively for the digits between 10 to 99.
                if ( (temp >= 10) && (temp < 100) ) {
                    if ( (temp/10) == k )   count++;
                    if ( (temp%10) ==k )    count++;
                } else {    // Check the ones place only for other cases.
                    if ( (temp%10) == k )
                        count++;
                }
                
                temp /= 10;
            } while (temp >= 10);
        }

        return count;        
    }

 

 

[Algorithm] 3. Digit Counts

标签:nes   code   one   ++   des   col   esc   cti   lse   

原文地址:https://www.cnblogs.com/jjlovezz/p/9915780.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!