与之呼应

文章 评论 浏览 29

与之呼应 2022-05-04 13:56:58

从小到大
[3, 15, 8, 29, 102, 22].sort((a,b) => a-b)
从大到小
[3, 15, 8, 29, 102, 22].sort((a,b) => b-a)

第 43 题:使用 sort() 对数组 [3, 15, 8, 29, 102, 22] 进行排序,输出结果

与之呼应 2022-05-03 23:55:07
//暴力版本
function NumberOf1Between1AndN(n){
	let count = 0;
    for (let i = 0; i <= n; i++) {
        let temp = i;
        while (temp > 0) {
            if (Math.floor(temp % 10) == 1) {
                count++;
            }
            temp /= 10;
        }
    }
    return count;
}
//跑过测试,复杂度为O(logn)版本
var countDigitOne = function(n) {
   if (n < 1)
        return 0;
    let count = 0,
        base = 1,
        round = n;
    while (round > 0) {
        let weight = Math.floor(round % 10);
        round = Math.floor(round / 10);
        count += Math.floor(round * base);
        if (weight == 1)
            count += Math.floor(n % base) +1;
        else if (weight > 1)
            count += base;
        base *= 10;
    }
    return count;
};

第 121 题:统计 1 ~ n 整数中出现 1 的次数

更多

推荐作者

櫻之舞

文章 0 评论 0

弥枳

文章 0 评论 0

m2429

文章 0 评论 0

野却迷人

文章 0 评论 0

我怀念的。

文章 0 评论 0

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文