论坛首页 招聘求职论坛

深圳两个上机题,求讨论!

浏览 31618 次
精华帖 (0) :: 良好帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2010-10-08  
我最然没有前面那些大哥们的思想 但是还是写了一个
import java.util.HashMap;
import java.util.Map;

public class Mianshi {
	public static boolean find1_9(String str){
		Map<String,Integer> map = new HashMap<String, Integer>();
		for(int i = 0;i<str.length();i++){
			switch(str.charAt(i)){
			case '1' : 
				if(map.containsKey("1")){
					map.put("1",map.get("1")+1);
				}else{
					map.put("1", 1);
				}
				break;
			case '2' : 
				if(map.containsKey("2")){
				map.put("2",map.get("2")+1);
			}else{
				map.put("2", 1);
			}
			break;
			case '3' : 
				if(map.containsKey("3")){
				map.put("3",map.get("3")+1);
			}else{
				map.put("3", 1);
			}
			break;
			case '4' : 
				if(map.containsKey("4")){
				map.put("4",map.get("4")+1);
			}else{
				map.put("4", 1);
			}
			break;
			case '5' : 
				if(map.containsKey("5")){
				map.put("5",map.get("5")+1);
			}else{
				map.put("5", 1);
			}
			break;
			case '6' : 
				if(map.containsKey("6")){
				map.put("6",map.get("6")+1);
			}else{
				map.put("6", 1);
			}
			break;
			case '7' : 
				if(map.containsKey("7")){
				map.put("7",map.get("7")+1);
			}else{
				map.put("7", 1);
			}
			break;
			case '8' : 
				if(map.containsKey("8")){
				map.put("8",map.get("8")+1);
			}else{
				map.put("8", 1);
			}
			break;
			case '9' : 
				if(map.containsKey("9")){
				map.put("9",map.get("9")+1);
			}else{
				map.put("9", 1);
			}
			break;
			}
		}
		if(map.size() == 9){
			Integer flag = -1;
			for(String key : map.keySet()){
				Integer value = map.get(key);
				if(value!=1){
					flag = 1;
					break;
				}
			}
			if(flag==-1){
				return true;
			}
		}else{
			return false;
		}
		return false;
	}
	public static void main(String[] args) {
		for(int i = 100;i<=333;i++){
			for(int j = 200;j<=666;j++){
				for(int k = 300;k<=999;k++){
					if((2*i == j) && (3*i == k)){
						String temp = "" + i + j +k;
						boolean flag = find1_9(temp);
						if(flag){
							System.out.println(i +" = " + j +" = " + k);
						}
					}
				}
			}
		}
	}
}


0 请登录后投票
   发表时间:2010-10-08  
学习中。。。。je牛人多啊。。。
0 请登录后投票
   发表时间:2010-10-08   最后修改:2010-10-08

实在看不懂前几个大哥写的逆波兰表达式,自己粗写了一个,也算是学习了一下,没有做字符串的初始化和加入全部运算符,但是要用的人改改容易完善

package com.ll.test;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.StringTokenizer;
/**
 * 
 * @author LiuLiu
 *
 */
public class CalculateString {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		AnalyzingExpression ae = new AnalyzingExpression(
				"4-(4-3*5+(2*4)+100)/10");
		ae.toRight();
		ae.getResult();
	}

}

class AnalyzingExpression {
	private String e = "4-(4-3*5+(2*4)+100)/10";
	private ArrayList<String> ori = new ArrayList<String>();
	private ArrayList<String> right = new ArrayList<String>();
	private String result;

	public ArrayList<String> getRight() {
		return right;
	}

	public AnalyzingExpression(String input) {
		StringTokenizer st = new StringTokenizer(input.replaceAll(" ", ""),
				"+-*/()", true);
		while (st.hasMoreElements()) {
			ori.add(st.nextToken());
		}
	}

	public void toRight() {
		Stack<String> s = new Stack<String>();// 运算符栈
		int position = 0;
		while (true) {
			String currentOriEle = ori.get(position);
			if (Calculate.isOperator(currentOriEle)) {// 如果是运算符需要处理
				if (s.empty() || currentOriEle.equals("(")) {// 如果是空栈,或者是"("直接入栈
					s.push(currentOriEle);
				} else if (currentOriEle.equals(")")) {// 若为')',出栈并顺序输出运算符直到遇到第一个'(',遇到的第一个'('出栈但不输出;
					while (!s.empty()) {
						if (s.peek().equals("(")) {
							s.pop();
							break;
						} else {
							right.add(s.pop());
						}
					}
				} else {// 若为其它,比较stackOperator栈顶元素与当前元素的优先级:如果栈顶元素是'(',当前元素入栈;如果栈顶元素
					// >= 当前元素,出栈并顺序输出运算符直到 栈顶元素 < 当前元素,然后当前元素入栈; 如果 栈顶元素 <
					// 当前元素,直接入栈。
					if (s.peek().equals("(")) {
						s.push(currentOriEle);
					} else {
						while (!s.empty()
								&& Calculate.priority(currentOriEle) <= Calculate
										.priority(s.peek())) {
							right.add(s.pop());
						}
						s.push(currentOriEle);
					}
				}
			} else {// 数字直接进list
				right.add(currentOriEle);
			}
			position++;
			if (position >= ori.size())
				break;
		}
		while (!s.empty()) {// 运算符栈不为空入list
			right.add(s.pop());
		}
	}

	// 对右序表达式进行求值
	public void getResult() {
		Stack<Double> s = new Stack<Double>();
		double n1 = 0;
		double n2 = 0;
		String e = null;
		Iterator<String> it = right.iterator();

		while (it.hasNext()) {
			e = it.next();
			if (Calculate.isOperator(e)) {
				n1 = s.pop();
				n2 = s.pop();
				s.push(Calculate.twoResult(e, n1, n2));
			} else
				s.push(Double.parseDouble(e));
		}
		result = String.valueOf(s.pop());
		it = right.iterator();
		while (it.hasNext()) {
			System.out.print(it.next());
		}
		System.out.println("=" + result);
	}
}

class Calculate {
	public static boolean isOperator(String operator) {
		if ("+-*/()".contains(operator)) {
			return true;
		} else {
			return false;
		}
	}

	public static int priority(String operator) {
		if ("+-".contains(operator))
			return 3;
		else if ("(".contains(operator))
			return 1;
		else if ("*/".contains(operator))
			return 5;
		else
			return 0;
	}

	public static double twoResult(String operator, double y, double x) {
		try {
			double z = 0;
			if (operator.equals("+"))
				z = x + y;
			else if (operator.equals("-"))
				z = x - y;
			else if (operator.equals("*"))
				z = x * y;
			else if (operator.equals("/"))
				z = x / y;
			else
				z = 0;
			return z;
		} catch (NumberFormatException e) {
			throw e;
		}
	}
}

class Stack<T> {
	private LinkedList<T> ll = new LinkedList<T>();

	public void push(T e) {
		ll.addFirst(e);
	}

	public T pop() {
		return ll.removeFirst();
	}

	public T peek() {
		return ll.getFirst();
	}

	public boolean empty() {
		return ll.isEmpty();
	}
}
0 请登录后投票
   发表时间:2010-10-08  
楼上的童鞋试试-1/-3,写的这个不支持负数啊
0 请登录后投票
   发表时间:2011-04-08  
第一题算法

public class ExpressionCalc {
	
	public static final char MUL = '*';
	
	public static final char DIV = '/';
	
	public static final char SUB = '-';
	
	public static final char ADD = '+';	
	
	public static final char BRACKET_LEFT = '(';
	
	public static final char BRACKET_RIGHT = ')';
	
	public static Map<Character, String> keys = new HashMap<Character, String>();
	
	static {
		
		keys.put(MUL, "multiply");
		
		keys.put(DIV, "divide");
		
		keys.put(SUB, "subtract");
		
		keys.put(ADD, "add");
	}
	
	public static int getPreIndex(StringBuilder sb, int index) {
		
		for (int i = index - 1; i >= 0; i--) {
			
			if (keys.containsKey(sb.charAt(i))) {
				
				// 处理负数的情况,如: -376 (乘/除/加/减) 1472
				if (keys.containsKey(sb.charAt(i - 1)) || sb.charAt(i - 1) == BRACKET_LEFT) {
					
					continue;
				}
				
				return i + 1;
			}
		}
		
		return 1;
	}
	
	public static int getPostIndex(StringBuilder sb, int index) {
		
		int len = sb.length();
		
		for (int i = index + 1; i < len; i++) {
			
			if (keys.containsKey(sb.charAt(i))) {
				
				// 处理负数的情况,如: 376 (乘/除/加/减) -1472
				if (keys.containsKey(sb.charAt(i - 1)) && !keys.containsKey(sb.charAt(i + 1))) {
					
					continue;
				}
				
				return i;
			}
		}
		
		return len - 1;
	}
	
	public static String evalExpression(String expression) throws Exception {
		
		StringBuilder sb = new StringBuilder();
		
		sb.append(expression);
		
		// 乘除运算优先最高
		for (int i = 1; i < sb.length() - 1; i++) {
			
			if (sb.charAt(i) == MUL || sb.charAt(i) == DIV) {
				
				int preInd = getPreIndex(sb, i);
				
				int postInd = getPostIndex(sb, i);
				
				BigDecimal a = new BigDecimal(sb.substring(preInd, i));
				
				BigDecimal b = new BigDecimal(sb.substring(i + 1, postInd));
				
				if (sb.charAt(i) == MUL) {
					
					a = (BigDecimal) a.getClass().getDeclaredMethod(keys.get(sb.charAt(i)), BigDecimal.class).invoke(a, b);
					
				} else if (sb.charAt(i) == DIV) {
					
					a = (BigDecimal) a.getClass().getDeclaredMethod(keys.get(sb.charAt(i)), BigDecimal.class, int.class, int.class).invoke(a, b, 2, BigDecimal.ROUND_HALF_UP);
				}
				
				sb.replace(preInd, postInd, a.toString());
				
				i = 1;
			}
		}
		
		//  加减运算优先最低
		for (int i = 1; i < sb.length() - 1; i++) {
			
			if (sb.charAt(i) == SUB || sb.charAt(i) == ADD) {
				
				int preInd = getPreIndex(sb, i);
				
				int postInd = getPostIndex(sb, i);
				
				BigDecimal a = new BigDecimal(sb.substring(preInd, i));
				
				BigDecimal b = new BigDecimal(sb.substring(i + 1, postInd));
				
				a = (BigDecimal) a.getClass().getDeclaredMethod(keys.get(sb.charAt(i)), BigDecimal.class).invoke(a, b);
				
				sb.replace(preInd, postInd, a.toString());
				
				i = 1;
			}
		}
		
		return sb.substring(1, sb.length() - 1);
	}

	public static void main(String[] args) throws Exception {
		
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

		System.out.print("please input an expression : ");
		
		String expression = br.readLine();

		StringBuilder sb = new StringBuilder();
		
		sb.append(BRACKET_LEFT);
		
		sb.append(expression);
		
		sb.append(BRACKET_RIGHT);
		
		Stack<Integer> track = new Stack<Integer>();
		
		for (int i = 0, x, y; i < sb.length(); i++) {
			
			if (sb.charAt(i) == BRACKET_LEFT) {
				
				track.push(i);
				
			} else if (sb.charAt(i) == BRACKET_RIGHT) {
				
				x = track.pop();
				
				y = i + 1;
				
				sb.replace(x, y, evalExpression(sb.substring(x, y)));
				
				i -= (y - x);
			}
		}
		
		System.out.printf("calc expression \" %s \" result is : %s\n", expression, sb);
	}
}
0 请登录后投票
   发表时间:2011-04-09  
第二题算法

public class ExhaustionNumberArrange {

	public static String[] array = { "1", "2", "3", "4", "5", "6", "7", "8", "9" };
	
	public static boolean isContainSameChar(StringBuilder sb, String s) {
		
		for (int i = s.length() - 1; i >= 0; i--) {
			
			String v = Character.toString(s.charAt(i));
			
			if ("0".equals(v) || sb.indexOf(v) != -1 || s.indexOf(v) != i) {
				
				return true;
			}
		}
		
		return false;
	}
	
	public static void exhaustion(StringBuilder sb, int length) {
		
		for (int i = 0; i < array.length; i++) {
			
			if (sb.indexOf(array[i]) != -1) {
				
				continue;
			}
			
			sb.append(array[i]);
			
			length++;
			
			int pivot = Integer.parseInt(sb.toString());
			
			if (length < 3 && pivot > 33) {
				
				break;
				
			} else if (length < 3 && pivot < 33) {
				
				exhaustion(sb, length);
				
			} else {
				
				String v1 = Integer.toString(pivot * 2);
				
				String v2 = Integer.toString(pivot * 3);
				
				if (!isContainSameChar(sb, v1 + v2)) {
					
					System.out.printf("%d,%s,%s\n", pivot, v1, v2);
				}
			}
			
			sb.deleteCharAt(--length);
		}
	}
	
	public static void main(String[] args) {

		StringBuilder sb = new StringBuilder();
		
		exhaustion(sb, 0);
	}
}
0 请登录后投票
   发表时间:2011-04-12  
JE牛人多啊!佩服!
0 请登录后投票
   发表时间:2011-04-13  
public class SimpleCalculator
{
    static String calc(String expression, String pattern)
    {
        expression = expression.replaceAll("\\s+", "");
        Pattern p = Pattern.compile(pattern);
        Matcher m = p.matcher(expression);
        while (m.find())
        {
            int left = Integer.parseInt(m.group(1));
            int op = m.group(2).charAt(0);
            int right = Integer.parseInt(m.group(3));
            Integer value = null;
            switch (op)
            {
                case '*': value = left * right; break;
                case '/': value = left / right; break;
                case '+': value = left + right; break;
                case '-': value = left - right; break;
                case '%': value = left % right; break;
            }
            expression = expression.replaceFirst(pattern, value + "");
            m = p.matcher(expression);
        }
        return expression;
    }
    public static void main(String[] args)
    {
        String expression = "11 % 3 + 8+-2+ (2* 3) + (6- -2)/2";
        String[] patterns = new String[] { "\\((\\-{0,1}\\d+)([\\%\\*\\/\\+\\-](\\-{0,1}\\d+))\\)", "(\\-{0,1}\\d+)([\\%\\*\\/](\\-{0,1}\\d+))", "(\\-{0,1}\\d+)([\\+\\-](\\-{0,1}\\d+))" };
        for (String pattern : patterns)
        {
            expression = calc(expression, pattern);
        }
        System.out.println(expression);
    }
}
0 请登录后投票
   发表时间:2011-04-14   最后修改:2011-04-14
1. 给几个歪门邪道的解法
1)借助其他力量,如数据库:
public int exec (String exp) {
    return executeSQL ("select " + exp + " from dual");
} 

2)借助脚本引擎,LS有位童鞋已经给出了。
3) 借助java本身
// 该方法可使用与任意符合java语法的表达式
public Object exec (String exp) {
   // 先生成一个临时的类,类名随机
   String className = "C" + ((int)(Math.radom () * 10000));
   String content = "public class " + className + " {";
   content += "public Object exec () {";
   content += "return " + exp + ";}}";

   // 输出类文件
   File file = new File (System.getProperty ("user.dir"), className + ".java");
   FileWriter writer = new FileWriter (file);
   writer.write (conent);
   write.flush ();
   write.close ();

   // 编译这个类
   File outdir = new File (System.getProperty ("tmp.dir"), "out");
   if (!outdir.exist()) outdir.mkdirs ();
   com.sun.tools.compile.Main.compile ("-d ", oudir.getAbsolutePath(), file.getAbsolutePath());
   // 加载类
   URL url = new URL ("file", outdir.getAbsolutePath () + "/");
   URLClassLoader loader = new URLClassLoader (new URL[] {url}, this.getClass().getClassLoader());
   Class clazz = loader.load (className);
   // 执行
   Method m = clazz.getMethod ("exec");
   Object instance = clazz.newInstance ();
   return m.invoke (instance);

   // 清除临时文件
   file.delete();
}
0 请登录后投票
   发表时间:2011-04-16  
楼上也是高人啊,O(∩_∩)O哈哈~
0 请登录后投票
论坛首页 招聘求职版

跳转论坛:
Global site tag (gtag.js) - Google Analytics