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

  • 相关阅读:
    codeforces707B:Bakery
    codeforces707A:Brain's Photos
    BZOJ1084 [SCOI2005]最大子矩阵
    BZOJ1264 [AHOI2006]基因匹配Match
    BZOJ2764 [JLOI2011]基因补全
    codevs1257 打砖块
    BZOJ1079 [SCOI2008]着色方案
    BZOJ1026 [SCOI2009]windy数
    菜鸟学自动化测试(一)----selenium IDE
    关于w3school的html5部分output 元素实例代码(点亲自试一试进去)的问题纠正
  • 原文地址:https://www.cnblogs.com/caijing/p/3373158.html
Copyright © 2011-2022 走看看