由题知,需要使用0-9的2021张卡片
思路一:(循环枚举,数组卡片-1)
设定 cards数组,长度为10(因为从0开始数到9一共有10个位置),使用for循环为每个空间存入2021张卡片。
枚举从1到+无穷的数(假设为temp),进入循环体,当其不为0时,除余10,(每次除余10,能得到这个数个位上的数。)由于我们得到了一个 单个数字,将其放入 if 判断中,如果 (arr [ temp ] > 0)则代表,这个数在卡片数组中还有有值,我们将其减 1 ,减1的目的=抽走一张卡片。然后将 temp /10
(除10的原因在于将刚才获取到的各位去除,例如 251%10 = 1 , 251 /10 = 25),这样就可以将我们每一个循环得到的数temp的每一位获取到,并将起在数组中拿走它对应的卡片,此时插入判断条件,当卡片数组对应值 – 时 == 0 ,则终止循环,输出 temp 值。
具体代码如下:
public static int violence() {
//定义卡片数组
int cards [] = new int [10];
//存储余数
int count = 0;
//for循环存储卡片数
for (int i = 0; i < cards.length; i++) {
cards[i] = 2021;
}
//无限枚举数值 ++
for (int i = 1 ;; i++) {
//获取数值
int temp = i;
//判断temp进入循环条件,由于是0卡片的减少是在循环内执行的,所以不用担心误判
while (temp != 0) {
//获取个位数操作
count = temp % 10;
//整个循环出口
if (cards[count] <= 0) {
//当数组减少为0后 i 还进行了一次自增操作所以 这儿的 i要-1
System.out.println(i - 1);
return temp -1;
}
//对应卡牌总数减少
cards[count]--;
//除10,去掉已经操作过的 个位数
temp/=10;
}
}
}
思路二:(字符数组)
public static int CharacterArray() {
//一样设立卡片数组
int cards [] = new int [10];
//给卡片牌数赋值
for (int i = 0; i < cards.length; i++) {
cards[i] = 2021;
}
//定义存储结果
int res = 1;
//循环变量
while (res != 0) {
//将res转换为字符穿//分割为字符数组
String str [] = String.valueOf(res).split("");
//遍历字符数组
for (int i = 0; i < str.length; i++) {
//将获取到的单个字符,转为int类型
int temp = Integer.parseInt(str[i]);
//到对应的牌堆中-牌
if (cards[temp] > 0) {
cards[temp]--;
}else {
System.out.println(res - 1);
return res;
}
}
res++;
}
return res;
}
方法三(仔细观察发现,其实所有卡片中,总是 1 先进行消耗,所以在相同的卡片数量下,1肯定是最先花光的。)所以只需计算当2021个1用光以后是多少即可