逍遥骑士

天行健,君子以自强不息

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

Write a program that prints the numbers from 1 to 100. But for multiples of three print "Fizz" instead of the number and for the multiples of five print "Buzz". 
For numbers which are multiples of both three and five print "FizzBuzz". 

Additionally, instead of printing "Fizz" or "Buzz", create a lookup such that 3 --> "Fizz", 5 --> "Buzz", 7 --> "Woof" and so on. The signature of the method would be: 

List<String> fizzbuzz(int start, int end, Map<Integer, String> lookups) { ..} 

The expected output is of the format : 15:FizzBuzz, 21:FizzWoof, 105: FizzBuzzWoof, etc

翻译:写一个用来打印数字1-100。但是如果数字是3的倍数,打印"Fizz",5的倍数打印"Buzz".如果同时是3和5的倍数,则打印"FizzBuzz". 

另外,创建一个映射比如 3 --> "Fizz", 5 --> "Buzz", 7 --> "Woof" 来代替"Fizz" 或者 "Buzz",方法签名应该为:

List<String> fizzbuzz(int start, int end, Map<Integer, String> lookups) { ..} 

输出格式为:15:FizzBuzz, 21:FizzWoof, 105: FizzBuzzWoof, 等...

 

分析:题目较为简单,参数和返回值类型都已经确定,代码结构大致为:两层循环,判断是否能整除map中的key,如果可以 add到list中;注意处理能整除过个的情况,

代码如下:

public class Fizzbuzz {

	public static void main(String[] args) {
		Map<Integer, String> map = new HashMap<Integer,String>();
		map.put(3, "Fizz");
		map.put(5, "Buzz");
		map.put(7, "Woof");
		fizzbuzz(1,105000,map);

	}
	
	public static List<String> fizzbuzz(int start, int end, Map<Integer, String> lookups) {
		List<String> list = new ArrayList<String>();
		Set<Integer> set = lookups.keySet();
		StringBuffer sb = new StringBuffer();
		for(int i=start;i<=end;i++){
			Iterator<Integer> it = set.iterator();
			while(it.hasNext()){
				int j = it.next();
				if(i>=j && i%j==0){
					if(sb.indexOf(":") == -1){
						sb.append(String.valueOf(i)+":"+lookups.get(j));
					}else{
						sb.append(lookups.get(j));
					}
				}
			}
			if(sb.length()>0){
				list.add(sb.toString());
			}
			sb.delete(0, sb.length());
		}
		System.out.println(list.toString());
		return list;
	} 

}

  

题目链接:http://www.careercup.com/question?id=5658804364509184

posted on 2013-10-16 23:26  逍遥骑士  阅读(505)  评论(0编辑  收藏  举报