题目描述:求出1~13的整数中1出现的次数,并算出100~1300的整数中1出现的次数?为此他特别数了一下1~13中包含1的数字有1、10、11、12、13因此共出现6次,但是对于后面问题他就没辙了。ACMer希望你们帮帮他,并把问题更加普遍化,可以很快的求出任意非负整数区间中1出现的次数(从1 到 n 中1出现的次数)。
function NumberOf1Between1AndN_Solution(n) {
// write code here
var high = n,
count = 0,
low, temp, i = 1;
if (n < 0) return;
while (high) {
high = parseInt(n / Math.pow(10, i)); // 计算高位数
temp = n % Math.pow(10, i); // 计算临时数
cur = parseInt(temp / Math.pow(10, i - 1)); // 计算当前位
low = temp % Math.pow(10, i - 1); // 计算低位数
if (cur == 0) {
count += high * Math.pow(10, i - 1); // 如31023,对于百位数,高位为0-30共31个数
} else if (cur == 1) {
count += high * Math.pow(10, i - 1) + low + 1; // 如31123,对于百位数,高位为0-30共31个数,低位为0-23
} else {
count += (high + 1) * Math.pow(10, i - 1); // 如31223,对于百位数,高位为0-31共31个数
}
i++; //
}
return count;
}
// 暴力解法
function NumberOf1Between1AndN_Solution(n) {
// write code here
if (n < 0) return;
var count = 0;
for (var i = 1; i <= n; i++) {
var number = i;
while (number) {
if (number % 10 == 1) {
count++;
}
number = Math.floor(number / 10);
// number = parseInt(number / 10); 两种写法均可
}
}
return count;
}
网友评论