与之呼应 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;
};
- 共 1 页
- 1
从小到大
[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] 进行排序,输出结果