• (medium)LeetCode 233.Number of Digit One


    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;
        }
    }
    

      

     运行结果:

     

  • 相关阅读:
    cocos2dx遇到的一些坑
    cocos2dx场景切换的坑
    整合quickx到普通cocos2dx
    Hadoop、spark
    Redis高级特性及应用场景
    wpf相关好资源
    MVVM模式的几个开源框架
    ASP.NET的IIS映射
    NET 开发者必备的工具箱
    C#开源汇总
  • 原文地址:https://www.cnblogs.com/mlz-2019/p/4703007.html
Copyright © 2020-2023  润新知