首页 > 其他 > 详细

微软编程一小时题目1 : Arithmetic Expression

时间:2014-04-13 06:46:28      阅读:429      评论:0      收藏:0      [点我收藏+]
时间限制:2000ms
单点时限:200ms
内存限制:256MB

描述

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!