import java.util.Scanner
/**
* 使用递归法统计整数 number 有多少个 bitNum 数字
*/
fun count(number: Int, bitNum: Int): Int {
var times = 0
if (number <= 0) {
return 0
}
if (number % 10 == bitNum) {
++times
}
times += count(number / 10, bitNum) // 使用递归检测其他位上的数字
return times
}
/**
* 输出 1 到 number 之间出现次数最多的数字,以及出现次数
*/
fun main(/*args: Array<String>*/) {
print("请输入上限整数:")
val scanner = Scanner(System.`in`)
val n = scanner.nextInt()
var t = 0
val tLst: MutableList<Int> = mutableListOf()
var max = 0
for (x in 0..9) {
for (i in 1..n) {
t += count(i, x)
}
if (t > max) {
max = t
}
tLst.add(t)
t = 0
}
print("从 1 至 $n 的所有整数中,数字 0 ~ 9 出现次数最多的是 ")
for (i in tLst.indices) {
if (tLst[i] == max) {
print("$i ")
}
}
println(", 次数为 $max 次")
}
统计从1到给定整数之间所有整数中出现次数最多的数字
于 2023-10-23 22:16:05 首次发布