From 72bd8f1c1d91943c425fd5a5f18c5f61708310d9 Mon Sep 17 00:00:00 2001 From: huangge1199 Date: Fri, 13 Aug 2021 14:37:42 +0800 Subject: [PATCH] =?UTF-8?q?233:=E6=95=B0=E5=AD=97=201=20=E7=9A=84=E4=B8=AA?= =?UTF-8?q?=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../leetcode/editor/cn/NumberOfDigitOne.java | 58 +++++++++++++++++++ .../leetcode/editor/cn/NumberOfDigitOne.md | 26 +++++++++ 2 files changed, 84 insertions(+) create mode 100644 src/main/java/leetcode/editor/cn/NumberOfDigitOne.java create mode 100644 src/main/java/leetcode/editor/cn/NumberOfDigitOne.md diff --git a/src/main/java/leetcode/editor/cn/NumberOfDigitOne.java b/src/main/java/leetcode/editor/cn/NumberOfDigitOne.java new file mode 100644 index 0000000..768ca87 --- /dev/null +++ b/src/main/java/leetcode/editor/cn/NumberOfDigitOne.java @@ -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) + +} \ No newline at end of file diff --git a/src/main/java/leetcode/editor/cn/NumberOfDigitOne.md b/src/main/java/leetcode/editor/cn/NumberOfDigitOne.md new file mode 100644 index 0000000..2648bbd --- /dev/null +++ b/src/main/java/leetcode/editor/cn/NumberOfDigitOne.md @@ -0,0 +1,26 @@ +

给定一个整数 n,计算所有小于等于 n 的非负整数中数字 1 出现的个数。

+ +

 

+ +

示例 1:

+ +
+输入:n = 13
+输出:6
+
+ +

示例 2:

+ +
+输入:n = 0
+输出:0
+
+ +

 

+ +

提示:

+ + +
Related Topics
  • 递归
  • 数学
  • 动态规划
  • \n
  • 👍 278
  • 👎 0
  • \ No newline at end of file