导航

(medium)LeetCode 233.Number of Digit One

Posted on 2015-08-04 20:13  骄阳照林  阅读(109)  评论(0编辑  收藏  举报

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.

解法:参考编程之美 132页 2.4 1的数目,以下代码中,注意iFactor有可能超越int所能表示的范围,故将其类型定义为long,为了避免过多的强制类型转换,其他变量也定义为long,但是iCurNum除外,switch()中变量不能为long类型。(以下以百位数1的个数为例)

百位数为0:百位数上可能出现的1的次数由高位决定,=更高位数*当前权值(100);受高位影响

百位数为1:=低位数字+1  +百位数为0的情况;受高位和低位影响

百位数大于1:(高位数+1)*当前权值(100);受高位影响

 

        

代码如下:

public class Solution {
    public int countDigitOne(int n) {
        if(n<=0) return 0;
        long iCount=0;
        long iFactor=1;
        long iLowerNum=0;
        int iCurrNum=0;
        long iHigherNum=0;
        while(n/iFactor!=0){
            iLowerNum=n-(n/iFactor)*iFactor;
            iCurrNum=(int)(n/iFactor)%10;
            iHigherNum=n/(iFactor*10);
            switch(iCurrNum){
                case 0:
                    iCount=iCount+iHigherNum*iFactor;
                    break;
                case 1:
                    iCount+=iHigherNum*iFactor+iLowerNum+1;
                    break;
                default:
                    iCount+=(iHigherNum+1)*iFactor;
                    break;
            }
            iFactor*=10;
        }
        return (int)iCount;
    }
}

  

 运行结果: