Given N arithmetic expressions, can you tell whose result is closest to 9?
Line 1: N (1 <= N <= 50000).
Line 2..N+1: Each line contains an expression in the format of "a op b" where a, b are integers (-10000 <= a, b <= 10000) and op is one of addition (+), subtraction (-), multiplication (*) and division (/). There is no "divided by zero" expression.
The index of expression whose result is closest to 9. If there are more than one such expressions, output the smallest index.
4 901 / 100 3 * 3 2 + 6 8 - -1
2
package ArithmeticExpression;
import java.io.IOException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws IOException {
long start = System.currentTimeMillis();
Scanner sc = new Scanner(System.in);
// int num = Integer.parseInt(sc.nextLine());
//也可以
int num = sc.nextInt();
sc.nextLine();
String []strline = new String[num];
for(int i=0;i<num;i++){
if(sc.hasNextLine()){
strline[i]=sc.nextLine();
System.out.println(strline[i]);
}
}
sc.close();
double []answer = new double[num];
int count = 0;
String [] str = new String[3];
for(int i = 0;i<num;i++){
str = strline[i].split(" ");
if(str[1].equals("+"))
answer[count] = Math.abs(Double.parseDouble(str[0]) + Double.parseDouble(str[2])-9);
else if(str[1].equals("-"))
answer[count] = Math.abs(Double.parseDouble(str[0]) - Double.parseDouble(str[2])-9);
else if(str[1].equals("*"))
answer[count] = Math.abs(Double.parseDouble(str[0]) * Double.parseDouble(str[2])-9);
else if(str[1].equals("/"))
answer[count] = Math.abs(Double.parseDouble(str[0]) / Double.parseDouble(str[2])-9);
count ++;
}
Double min =answer[0];
int flag = 0;
for(int j=1;j<num;j++){
if(min>answer[j]){
min = answer[j];
flag = j;
}
}
System.out.println(flag+1);
long end = System.currentTimeMillis();
System.out.println(end - start + "ms");
}
}
微软编程一小时题目1 : Arithmetic Expression,布布扣,bubuko.com
微软编程一小时题目1 : Arithmetic Expression
原文:http://blog.csdn.net/lsp1991/article/details/23556073