Merchant‘s Guide To The Galaxy使用java解法

题目描述

大意就是我成了地球首富,然后有很多钱,但是地球已经不适合人类居住了,需要跑到银河系去做生意,但是银河系使用的是罗马字母表示钱,所以座位程序员的我打算自己写一个罗马字母和十进制数字互转的小程序,以帮助我做生意。

罗马字母有: I,V,X,L,C,D,M

转换规则

1. I:可以表示十进制数字1,V:可以表示十进制数字5,X:可以表示十进制数字10,L:可以表示十进制数字50,C:可以表示十进制数字100,D:可以表示十进制数字500,M:可以表示十进制数字1000;

2.I, X, C, and M可以重复出现最多3次;

3.一般是从后往前排列:即MDCLXVI的顺序,当然也允许相邻的两个倒序,但是需要符合以下规则:

   I :只能组合IV ,IX

   X:只能组合XL,XC

   C:只能组合CD,CM

   V,L,D不能倒序

Test input:

glob is I

prok is V

pish is X

tegj is L

glob glob Silver is 34 Credits

glob prok Gold is 57800 Credits

pish pish Iron is 3910 Credits

how much is pish tegj glob glob ?

how many Credits is glob prok Silver ?

how many Credits is glob prok Gold ?

how many Credits is glob prok Iron ?

how much wood could a woodchuck chuck if a woodchuck could chuck wood ?

 

Test Output:

pish tegj glob glob is 42

glob prok Silver is 68 Credits

glob prok Gold is 57800 Credits

glob prok Iron is 782 Credits

I have no idea what you are talking about

解题


public class Roman {
	char sysbol;
	int value;
	
	//only I,X,C,M can repeated
	boolean allowRepeat;
	
	//only I,X C can subtracted
	//such as: IV,IX; XL,XC;CD,CM
	boolean allowSubstracted;
	
	//if allow subtracted, how distence?
	//I,V,X,L,C,D,M
	//IV,IX:distence is 2;
	int substractedDestence;
	
	
	public char getSysbol() {
		return sysbol;
	}
	public void setSysbol(char sysbol) {
		this.sysbol = sysbol;
	}
	public int getValue() {
		return value;
	}
	public void setValue(int value) {
		this.value = value;
	}
	public boolean isAllowRepeat() {
		return allowRepeat;
	}
	public void setAllowRepeat(boolean allowRepeat) {
		this.allowRepeat = allowRepeat;
	}
	public boolean isAllowSubstracted() {
		return allowSubstracted;
	}
	public void setAllowSubstracted(boolean allowSubstracted) {
		this.allowSubstracted = allowSubstracted;
	}
	public int getSubstractedDestence() {
		return substractedDestence;
	}
	public void setSubstractedDestence(int substractedDestence) {
		this.substractedDestence = substractedDestence;
	}
	
	

}
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class RomanNumber {
	private char[] allowRomans=new char[] {
		'I',
		'V',
		'X',
		'L',
		'C',
		'D',
		'M'
	};
	private int[] vs = new int[]{
            1,
            5,
            10,
            50,
            100,
            500,
            1000
        };
	List<Roman> featuredRomans = new ArrayList<Roman>();
	public List<Roman> getRomans(){
		return featuredRomans;
	}
	
	public RomanNumber() {
		for (int i = 0; i < allowRomans.length; i++) {
        	Roman roman = new Roman();
        	roman.setSysbol(allowRomans[i]);
        	roman.setValue(vs[i]);
        	roman.setAllowRepeat(allowRomans[i] == 'I' || allowRomans[i] == 'X' || allowRomans[i] ==
                    'C' || allowRomans[i] == 'M');
        	roman.setAllowSubstracted(allowRomans[i] == 'I' || allowRomans[i] == 'X' || allowRomans[
                        i] == 'C');
        	roman.setSubstractedDestence((allowRomans[i] == 'I' || allowRomans[i] == 'X' ||
                        allowRomans[i] == 'C') ? 2 : 0);
        	featuredRomans.add(roman);
        }
	}
	
    	
        
        
    
    public int calculate(String exp) throws Exception {
        if (exp.equals("")) return 0;
        char[] romans = exp.toCharArray();
        int result = 0;
        if (romans.length == 1) {
        	for (Roman c : featuredRomans) {
				if(c.getSysbol() == romans[0])
					return c.getValue();
			}
        }
        for (int i = 0; i <= romans.length - 1; i = i + 2) {
        	Roman current=null;
        	for (Roman c : featuredRomans) {
				if(c.getSysbol() == romans[i])
					current=c;
			}
            if (i >= romans.length - 1) {
                result += current.getValue();
                break;
            }
            Roman next =null; 
            for (Roman c : featuredRomans) {
				if(c.getSysbol() == romans[i+1])
					next=c;
			}
            if (current == null) {
                throw new Exception("unexpected roman char:"+romans[i]);
            }
            if (next == null) {
                throw new Exception("unexpected roman char:"+romans[i + 1]);
            }
            if (current.getValue() > next.getValue()) {
                result += current.getValue();
                i--;
            } else if (current.getValue() == next.getValue()) {
                if (!current.isAllowRepeat()) {
                    throw new Exception("Not allow {0} repeate"+current.getSysbol());
                }
                int repeatedCount = 2;
                for (int j = i + 2; j < romans.length; j++) {
                    if (romans[j] != current.getSysbol()) break;
                    repeatedCount++;
                    if (repeatedCount > 3) {
                        throw new Exception("Not allow {0} repeated more than 3 times"+current.getSysbol());
                    }
                }
                result += current.getValue();
                i--;
            } else {
                result += next.getValue() - current.getValue();
            }
        }
        return result;
    }
	public static void main(String[] args) {
		Scanner scan = new Scanner(System.in);
        // 从键盘接收数据
 
        // 判断是否还有输入
		RomanNumber rn = new RomanNumber();
        if (scan.hasNextLine()) {
            String str2 = scan.nextLine();
            try {
				System.out.println("result为:" + rn.calculate(str2));
			} catch (Exception e) {
				e.printStackTrace();
			}
        }
        scan.close();
		
	}

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
galaxy 起源于07年的一个数据库导库项目,做一个增删改查的功能,只要几行代码就可以了,只要你会简单的sql语句,就能快速完成一个 功能,相比struts2和spring,着实方便多了. 如果觉得好用,就放弃ssh吧,加入到galaxy的阵营。 1. 完成一个用户管理功能? user.jsp ,这个页面用于新增,修改一个用户 <html> <head></head> <body> <% MyHashMap req = RequestUtil.getRequest(request); MyHashMap obj = new Query("select * from user where id ="+req.getInt("id")); %> <form action="regesiterAction.jsp" method="post"> 用户名<input name="username" value="<%=obj.getString("username")%>" /> 密码<input type="password" value="<%=obj.getString("password")%>" name="password" /> 手机号: <input name="telphone" value="<%=obj.getString("username")%>" /> <input type="hidden" name="action" value="saveorupdate" /> <input type="submit" value="提交" /> </form> </body> </html> userAction.jsp <% MyHashMap req = RequestUtil.getRequest(request); if(req.getString("action").equals("saveorupdate")){ new Imp().saveOrUpdate(req); }else if(req.getString("action").equals("del")){ new Query().update("delete from user where id="+req.getString("id")); } response.sendRededict("user.jsp"); %> 用户列表页面 <html> <body> <form> <table> <tr><td>用户名</td><td>密码</td><td>手机号</td> <% MyHashMap req = RequestUtil.getReq(request); int pagesize = req.getInt("pagesize",10); int pageindex = req.getInt("pageindex",1); List<MyHashMap> list = new Query().getByPaging("select * from user where "+condition,pagesize,pageindex); MyHashMap pageinfo = list.get(0); for(MyHashMap map:list){ %> <tr> <td><%=map.getString("username")%></td> <td><%=map.getString("password")%></td> <td><%=map.getString("telphone")%></td> </tr> <%}%> </table> <%=com.zxhy.fxpt.common.util.StringUtil.getdaohang(pageinfo.getInt("pagecount"),pageinfo.getInt("pagenum"))%> </form> </body> </html> 有兴趣的话,跟我联系qq: 376860997
galaxy 起源于07年的一个数据库导库项目,做一个增删改查的功能,只要几行代码就可以了,只要你会简单的sql语句,就能快速完成一个 功能,相比struts2和spring,着实方便多了. 如果觉得好用,就放弃ssh吧,加入到galaxy的阵营。 1. 完成一个用户管理功能? user.jsp ,这个页面用于新增,修改一个用户 <html> <head></head> <body> <% MyHashMap req = RequestUtil.getRequest(request); MyHashMap obj = new Query("select * from user where id ="+req.getInt("id")); %> <form action="regesiterAction.jsp" method="post"> 用户名<input name="username" value="<%=obj.getString("username")%>" /> 密码<input type="password" value="<%=obj.getString("password")%>" name="password" /> 手机号: <input name="telphone" value="<%=obj.getString("username")%>" /> <input type="hidden" name="action" value="saveorupdate" /> <input type="submit" value="提交" /> </form> </body> </html> userAction.jsp <% MyHashMap req = RequestUtil.getRequest(request); if(req.getString("action").equals("saveorupdate")){ new Imp().saveOrUpdate(req); }else if(req.getString("action").equals("del")){ new Query().update("delete from user where id="+req.getString("id")); } response.sendRededict("user.jsp"); %> 用户列表页面 <html> <body> <form> <table> <tr><td>用户名</td><td>密码</td><td>手机号</td> <% MyHashMap req = RequestUtil.getReq(request); int pagesize = req.getInt("pagesize",10); int pageindex = req.getInt("pageindex",1); List<MyHashMap> list = new Query().getByPaging("select * from user where "+condition,pagesize,pageindex); MyHashMap pageinfo = list.get(0); for(MyHashMap map:list){ %> <tr> <td><%=map.getString("username")%></td> <td><%=map.getString("password")%></td> <td><%=map.getString("telphone")%></td> </tr> <%}%> </table> <%=com.zxhy.fxpt.common.util.StringUtil.getdaohang(pageinfo.getInt("pagecount"),pageinfo.getInt("pagenum"))%> </form> </body> </html> 有兴趣的话,跟我联系qq: 376860997
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值