Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

第 14题(2019-08-8):统计 1 ~ n 整数中出现 1 的次数. #9

Open
qappleh opened this issue Aug 8, 2019 · 1 comment
Open
Labels

Comments

@qappleh
Copy link
Owner

qappleh commented Aug 8, 2019

No description provided.

@qappleh
Copy link
Owner Author

qappleh commented Aug 9, 2019

分析归纳一下,按照每一位上的数字来分析
比如55, 个位可能产生的 1 是 6个(1, 11, 21, 31, 41, 51, 注意这里11只计算的个位的1), 十位5 可能产生的 1是 10个,(10 - 19, 这里的11只计算的十位的1);

比如222, 个位 可能产生的 1 是 23个(1, 11, 21, ... 221, 只关注个位), 十位2 可能产生的 1是 30个(10-19, 110-119, 210-219, 只关注十位), 百位2 产生的 1是100个(100 - 199, 只关注百位).

以此类推, 每一位数字可能产生的1的个数跟他的高位部分和低位部分相关:
其中0和1需要特殊处理,代码如下:

function countOne(n) {
    var factor = 1;
    let count = 0;
    let next = parseInt(n / factor);
    while (next !== 0) {
        var lower = n - next * factor
        var curr = next % 10;
        var high = parseInt(n / (10 * factor));

        if (curr === 0) {
            count += high * factor;
        } else if (curr === 1) {
            count += high * factor + lower + 1
        } else {
            count += (high + 1) * factor
        }

        factor *= 10;
        next = parseInt(n / factor);
    }
    return count;
}  

@qappleh qappleh added the js label Nov 27, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant