当前位置: 代码迷 >> 综合 >> 统计数字: 计算数字k在0到n中的出现的次数,k可能是0~9的一个值
  详细解决方案

统计数字: 计算数字k在0到n中的出现的次数,k可能是0~9的一个值

热度:5   发布时间:2023-12-16 06:39:47.0

例如n=12,k=1,在 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],我们发现1出现了5次 (1, 10, 11, 12)

n=12,k=12,在 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],我们发现12出现了1次 (12)

n=0,k=0,在 [0],我们发现0出现了1次 (0)

python代码

def digitCounts(k,n):count = 0for i in range(n+1):# 输入k=0if i == 0 and i == k:count += 1#其他情况while(i//10 >= 0 and i != 0):j = i % 10if j == k:count += 1i = i //10#k等于n自身if i != 0 and k == n:count += 1return countreturn countif __name__ == '__main__':#默认0,0输出1#1,12输出5#12,12输出1result = digitCounts(0, 0)print(result)

Java代码:

package test;public class StatisticalFigures {public static void main(String[] args) {System.out.println(digitCounts(12,6));}public static int digitCounts(int number,int key){int count = 0;for (int i = 0; i < number+1; i++) {if (key != 0) {if (i == 0 && i == key) {count += 1;}if (i != 0 && number == key) {count += 1;return count;}int temp = i;boolean geweiflag = true;while ((temp % key ) == 0 && temp != 0) {if (geweiflag == true) {int j = i % 10;if (key == j) {count += 1;}geweiflag = false;}else {if (key == temp) {count += 1;}}temp = temp / 10;}}else {boolean flag = true;int temp = i;if (flag == true) {int j = i % 10;if (key == j) {count += 1;}flag = false;}else {if (key == temp) {count += 1;}}}}	return count;}}