26 lines
792 B
Java
26 lines
792 B
Java
# 43. 从 1 到 n 整数中 1 出现的次数
|
|
|
|
[NowCoder](https://www.nowcoder.com/practice/bd7f978302044eee894445e244c7eee6?tpId=13&tqId=11184&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking&from=cyc_github)
|
|
|
|
## 解题思路
|
|
|
|
```java
|
|
public int NumberOf1Between1AndN_Solution(int n) {
|
|
int cnt = 0;
|
|
for (int m = 1; m <= n; m *= 10) {
|
|
int a = n / m, b = n % m;
|
|
cnt += (a + 8) / 10 * m + (a % 10 == 1 ? b + 1 : 0);
|
|
}
|
|
return cnt;
|
|
}
|
|
```
|
|
|
|
> [Leetcode : 233. Number of Digit One](https://leetcode.com/problems/number-of-digit-one/discuss/64381/4+-lines-O(log-n)-C++JavaPython)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
<div align="center"><img width="320px" src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/githubio/公众号二维码-2.png"></img></div>
|