代码拉取完成,页面将自动刷新
同步操作将从 doocs/leetcode 强制同步,此操作会覆盖自 Fork 仓库以来所做的任何修改,且无法恢复!!!
确定后同步将在后台操作,完成时将刷新页面,请耐心等待。
输入一个整数 n
,求 1 ~ n 这 n 个整数的十进制表示中 1 出现的次数。
例如,输入 12,1 ~ 12 这些整数中包含 1 的数字有 1、10、11 和 12,1 一共出现了 5 次。
示例 1:
输入:n = 12
输出:5
示例 2:
输入:n = 13
输出:6
限制:
1 <= n < 2^31
注意:本题与主站 233 题相同:https://leetcode-cn.com/problems/number-of-digit-one/
将 n 拆为两部分:最高位 high 和低位 lows。按 high 是否为 1 分别递归求解结果 f(n)。
以 n=3356 举例说明。
high=3,lows=356,base=1000。此时 n 可拆分为 0~999
,1000~1999
,2000~2999
,3000~3356
,其中:
因此,1 的总个数为 high*f(base-1)+f(lows)+base
。
最高位非 1 的情况,也可以按照同样的方法分析。
from functools import lru_cache
class Solution:
@lru_cache
def countDigitOne(self, n: int) -> int:
if n < 1:
return 0
s = str(n)
high = int(s[0])
base = pow(10, len(s) - 1)
lows = n % base
return self.countDigitOne(base - 1) + lows + 1 + self.countDigitOne(lows) if high == 1 else high * self.countDigitOne(base - 1) + base + self.countDigitOne(lows)
class Solution {
public int countDigitOne(int n) {
if (n < 1) {
return 0;
}
String s = String.valueOf(n);
int high = s.charAt(0) - '0'; // 最高位
int base = (int) Math.pow(10, s.length() - 1); // 基数
int lows = n % base; // 低位
return high == 1
? countDigitOne(base - 1) + countDigitOne(lows) + lows + 1
: high * countDigitOne(base - 1) + countDigitOne(lows) + base;
}
}
/**
* @param {number} n
* @return {number}
*/
var countDigitOne = function (n) {
let res = 0;
let i = 1;
while (i <= n) {
let high = ~~(n / i / 10);
let cur = ~~(n / i) % 10;
let low = n - ~~(n / i) * i;
switch (cur) {
case 0:
res += high * i;
break;
case 1:
res += high * i + low + 1;
break;
default:
res += (high + 1) * i;
}
i *= 10;
}
return res;
};
class Solution {
public:
int countDigitOne(int n) {
long long digit = 1;
int count = 0;
int high = n / 10;
int cur = n % 10;
int low = 0;
while (high != 0 || cur != 0) {
if (cur == 0) {
count += high * digit;
} else if (cur == 1) {
count += high * digit + low + 1;
} else {
count += (high + 1) * digit;
}
low += cur * digit;
cur = high % 10;
high /= 10;
digit *= 10;
}
return count;
}
};
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。