233:数字 1 的个数

This commit is contained in:
huangge1199 2021-08-13 14:37:42 +08:00
parent 1e59ea881a
commit 72bd8f1c1d
2 changed files with 84 additions and 0 deletions

View File

@ -0,0 +1,58 @@
//给定一个整数 n计算所有小于等于 n 的非负整数中数字 1 出现的个数
//
//
//
// 示例 1
//
//
//输入n = 13
//输出6
//
//
// 示例 2
//
//
//输入n = 0
//输出0
//
//
//
//
// 提示
//
//
// 0 <= n <= 2 * 109
//
// Related Topics 递归 数学 动态规划
// 👍 278 👎 0
package leetcode.editor.cn;
//233:数字 1 的个数
class NumberOfDigitOne {
public static void main(String[] args) {
//测试代码
Solution solution = new NumberOfDigitOne().new Solution();
//4
System.out.println(solution.countDigitOne(11));
//6
System.out.println(solution.countDigitOne(13));
}
//力扣代码
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public int countDigitOne(int n) {
int index = 1;
int count = 0;
while (index<=n){
count += (n / (index * 10)) * index + Math.min(Math.max(n % (index * 10) - index + 1, 0), index);
index *= 10;
}
return count;
}
}
//leetcode submit region end(Prohibit modification and deletion)
}

View File

@ -0,0 +1,26 @@
<p>给定一个整数 <code>n</code>,计算所有小于等于 <code>n</code> 的非负整数中数字 <code>1</code> 出现的个数。</p>
<p> </p>
<p><strong>示例 1</strong></p>
<pre>
<strong>输入:</strong>n = 13
<strong>输出:</strong>6
</pre>
<p><strong>示例 2</strong></p>
<pre>
<strong>输入:</strong>n = 0
<strong>输出:</strong>0
</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li><code>0 <= n <= 2 * 10<sup>9</sup></code></li>
</ul>
<div><div>Related Topics</div><div><li>递归</li><li>数学</li><li>动态规划</li></div></div>\n<div><li>👍 278</li><li>👎 0</li></div>