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

  • 相关阅读:
    mysql复习相关
    OpenStack三种类型的NAT转换
    openstack资料相关
    [转]Web 调试工具之 Advanced REST client
    [转]Aspose.Words.dll 将 Word 转换成 html
    [Android] 开发第十天
    [win10]遇坑指南
    [转]Explorer.exe的命令行参数
    [Android] 开发第九天
    [Android] 开发第八天
  • 原文地址:https://www.cnblogs.com/caijing/p/3373158.html
Copyright © 2011-2022 走看看