zoukankan      html  css  js  c++  java
  • (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;
        }
    }
    

      

     运行结果:

     

  • 相关阅读:
    iOS开发
    Xcode
    UITextField
    iOS
    过场动画
    iOS 网络状态监听和检查,
    线程互动,GCD小应用,(功能实现并代码聚集---加载动画,弹框AlertView定时消失。)
    drawRect: 小注
    FMDB_and_Sqlite3
    UIGestureRecognizer手势。
  • 原文地址:https://www.cnblogs.com/mlz-2019/p/4703007.html
Copyright © 2011-2022 走看看