zoukankan      html  css  js  c++  java
  • 【LeetCode & 剑指offer刷题】特殊数题1:43 1~n整数中1出现的次数 (233. Number of Digit One )

    【LeetCode & 剑指offer 刷题笔记】目录(持续更新中...)

    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.
    Example:
    Input: 13
    Output: 6
    Explanation: Digit 1 occurred in the following numbers: 1, 10, 11, 12, 13.
    思路:
     
     
    /*
    比如1在十位数时
    ->100 10
    ->200 20
    ...
    ->1600 160 (最后两位小于10时)
    ->161x 160 + x + 1 10 最后两位 < 20
    ->1650 160 + 10 (≥ 20
    */
    class Solution
    {
    public:
        int countDigitOne(int n)
        {
            int counter = 0;
            for(long i = 1; i<=n; i*=10) //i为1所在位数比如上例中的10,divider为除数,比如上例中的100,remainder为n除以divider的余数,比如上例中的后两位数
            {
                long divider = i * 10; //防止n过大导致i*10溢出
                int remainder = n%divider;
                if(remainder >= 2*i) counter += (n/divider) * i + i;
                else if(remainder >= i && remainder < 2*i) counter += (n/divider) * i + (n%divider) - i + 1;
                else counter += (n/divider)*i;
            }
           
            return counter;
        }
    };
     
     
  • 相关阅读:
    遗传算法求解旅行商(TSP)问题 -- python
    office 小技巧
    oracle创建dblink
    c# equals与==的区别
    两人之间的一些参数
    .net 枚举(Enum)使用总结
    SQL Server 日期的加减函数: DATEDIFF DATEADD
    jquery操作select
    AS3帮助手册
    Razor和HtmlHelper的使用意义
  • 原文地址:https://www.cnblogs.com/wikiwen/p/10225060.html
Copyright © 2011-2022 走看看