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

  • 相关阅读:
    图片上下左右居中
    点击滚动指定高度 屏幕滚动事件
    实例16 验证登录信息的合法性
    实例15 判断某一年是否为闰年
    实例14 实现两个变量的互换(不借助第3个变量)
    实例13 不用乘法运算符实现2*16
    实例12 用三元运算符判断奇数和偶数
    实例11 加密可以这样简单(位运算)
    实例10 自动类型转换与强制类型转换
    实例9 重定向输入流实现程序日志
  • 原文地址:https://www.cnblogs.com/caijing/p/3373158.html
Copyright © 2011-2022 走看看