Digit Counts
Posted 北叶青藤
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Digit Counts相关的知识,希望对你有一定的参考价值。
Count the number of k‘s between 0 and n. k can be 0 - 9.
Example
if n = 12
, k = 1
in
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
we have FIVE 1‘s (1, 10, 11, 12)
分析:
利用while 循环 + num % 10可以获取 num中的所有数字。
class Solution { /* * param k : As description. * param n : As description. * return: An integer denote the count of digit k in 1..n */ public int digitCounts(int k, int n) { int totalCount = 0; for (int i = 0; i <= n; i++) { totalCount += counts(k, i); } return totalCount; } public int counts(int k, int value) { int count = 0; if (value == 0 && k == 0) return 1; while (value != 0) { int remainder = value % 10; if (remainder == k) { count++; } value = value / 10; } return count; } };
以上是关于Digit Counts的主要内容,如果未能解决你的问题,请参考以下文章
Project Euler 63: Powerful digit counts
2021-11-04:计算右侧小于当前元素的个数。给你`一个整数数组 nums ,按要求返回一个新数组 counts 。数组 counts 有该性质: counts[i] 的值是 nums[i] 右(