zoukankan      html  css  js  c++  java
  • 字符串替换数字问题

    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

  • 相关阅读:
    第4次作业(条件)比较大小。第3次作业(条件)计算火车运行时间。
    GitHub搜索技巧
    flex实现左中固定不变,右边自适应
    JavaScript高级__原型继承+组合继承
    JavaScript高级__深入了解闭包
    JavaScript高级__执行上下文代码案例
    JavaScript中的显式原型链 prototype 和隐式原型 __proto__
    谷歌强大插件收集,持续更新。。。
    js中~~和^=
    vue自定义指令----directive
  • 原文地址:https://www.cnblogs.com/caijing/p/3373158.html
Copyright © 2011-2022 走看看