题目描述
小蓝特别喜欢 2,今年是公元 2020 年,他特别高兴。他很好奇,在公元 1 年到公元 2020 年(包含)中,有多少个年份的数位中包含数字 2?
代码描述
public class BeautifulTwo {
public static void main(String[] args) {
int count = 0;
for (int i = 1; i <= 2020; i++){
int temp = i;
// 判断千位是否含有2
if(temp / 1000 == 2){
// 有2即加
count++;
continue;
}
// 无2即求余1000
temp %= 1000;
// 判断百位是否含有2
if(temp /100 == 2){
count++;
continue;
}
temp %= 100;
// 判断十位是否含有2
if(temp / 10 == 2){
count++;
continue;
}
// 判断个位是否含有2
if (temp % 10 == 2){
count++;
}
}
System.out.println("在公元 1 年到公元 2020 年(包含)中共有:"+count+" 个年份的数位中包含数字 2");
}
}
运行截图
答案为:563
总结
Java版的美丽的2解法绝对不是一个最优解,只能算是一个不同的解题思路,纯属娱乐。要看解题速度还是得看python解法。如果大家有更好的Java版解法,欢迎交流学习!