Q1:卡片
题目:
思路:
创建一个数组,nums[10],nums[0]表示0这张卡片用掉了多少张,然后再从1开始遍历,如果数组中有任意一个超过了2021那么就到此结束,超过了就是拼不成输出上一个数字,恰好相等那就是这个数。具体看代码
代码:
public class 卡片 {
public static void main(String[] args) {
int[] nums = new int[10];
for (int i = 1; ; i++) {
//每一个数字需要多少个卡片
int x = i;
while (x > 0) {
nums[x % 10]++;
x /= 10;
}
for (int j = 0; j < 10; j++) {
if (nums[j] > 2021) {
System.out.println(i - 1); //超过了2021,就是上一个i
return;
}else if(nums[j] == 2021){//恰好等于2021,就是这个i
System.out.println(i); //3138
return;
}
}
}
}
}
Q3:字符统计
题目:
思路:
每一个字母都有他的ASCII码,A~Z是65~90,那么我们就可以创建一个长度为91的数组,用来统计每一个字母出现的次数。strs[91],strs[65]就表示A字母出现的次数。这样我们统计完了这些字母出现的次数之后,我们找到出现次数最多的那些字母,我们先找到strs[i]最大的那个数,然后再次遍历这个数组,看看那些是最多的直接输出就行了。
代码:
import java.util.Scanner;
public class 字符统计 {
public static void main(String[] args) {
int[] strs = new int[91];
Scanner sc = new Scanner(System.in);
String str = sc.next();
//统计每一个字母出现的次数
for (int i = 0; i < str.length(); i++) {
strs[str.charAt(i)] ++;
}
//出现最多的字母有多少次
int max = strs[65];
for (int i = 65; i <= 90 ; i++) {
if(strs[i] > max){
max = strs[i];
}
}
//输出出现最多的那些字母
for (int i = 65; i <= 90; i++) {
if(strs[i] == max){
System.out.print((char) i);
}
}
}
}