一、题目描述
给定一个设备编号区间[start, end],包含4或18的编号都不能使用,如:418、148、718不能使用,108可用。请问有多少可用设备编号?
解答要求
时间限制:1000ms, 内存限制:256MB
输入
两个整数start end(单空格间隔),用于标识设备编号区间,0 < start < end <= 100000
输出
一个整数,代表可用设备编号的数量
样例
输入样例 1
3 20
输出样例 1
15
提示
不能使用的设备编号为4、14、18
二、代码模板
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import static java.lang.System.in;
public class Main {
public static void main(String[] args) {
Scanner cin = new Scanner(in, StandardCharsets.UTF_8.name());
int start = cin.nextInt();
int end = cin.nextInt();
cin.close();
System.out.println(getNormalDeviceNum(start, end));
}
// 待实现函数,在此函数中填入答题代码
private static int getNormalDeviceNum(int start, int end) {
return 0;
}
}
三、个人代码结果
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import static java.lang.System.in;
public class Main {
public static void main(String[] args) {
Scanner cin = new Scanner(in, StandardCharsets.UTF_8.name());
int start = cin.nextInt();
int end = cin.nextInt();
cin.close();
System.out.println(getNormalDeviceNum(start, end));
}
// 待实现函数,在此函数中填入答题代码
private static int getNormalDeviceNum(int start, int end) {
int count =0;
for (int i = start; i <= end; i++) {
//拆分I
int sw = i / 100000;
int i1 = i % 100000;
int w = i1 / 10000;
int i2 = i1 % 10000;
int q = i2 / 1000;
int i3 = i2 % 1000;
int b = i3 / 100;
int i4 = i3 % 100;
int s = i4 / 10;
int g = i4 % 10;
List<Integer> list = new ArrayList<>();
list.add(sw);
list.add(w);
list.add(q);
list.add(b);
list.add(s);
list.add(g);
if (list.contains(4)){
continue;
}else if (list.get(0)*10+list.get(1)==18){
continue;
}else if (list.get(1)*10+list.get(2)==18){
continue;
}else if (list.get(2)*10+list.get(3)==18){
continue;
}else if (list.get(3)*10+list.get(4)==18){
continue;
}else if (list.get(4)*10+list.get(5)==18){
continue;
}else{
count +=1;
}
}
return count;
}
}
四、优化思路
直接简单粗暴的循环star与end之间的所有的数据,会有很多不必要的循环。
如:
含有4 | 含有18 |
---|---|
4 | 18 |
40~49 | 180~189 |
400~499 | 1800~1899 |
4000~4999 | 18000~18999 |
… | … |
设计避开不必要的循环,也是提高效率的途径。