leetcode-412

 Fizz Buzz

Write a program that outputs the string representation of numbers from 1 to n.

But for multiples of three it should output “Fizz” instead of the number and for the multiples of five output “Buzz”. For numbers which are multiples of both three and five output “FizzBuzz”.

此题比较简单

java代码:

public class Solution {
    public List<String> fizzBuzz(int n) {
        List<String> li=new LinkedList<String>();
        for(int i=1;i<=n;i++){
            if(i%5==0&&i%3==0){
                li.add("FizzBuzz");
            }
            else if(i%3==0){
                li.add("Fizz");
            }else if(i%5==0){
                li.add("Buzz");
            }else{
                String a=i+"";
                li.add(a);
            }
        }
        return li;
    }
}

  如果想要速度快点的话诀窍就是not using "%" operation,就是不要用%号。

java代码:

public class Solution {
    public List<String> fizzBuzz(int n) {
        List<String> ret = new ArrayList<String>(n);
        for(int i=1,fizz=0,buzz=0;i<=n ;i++){
            fizz++;
            buzz++;
            if(fizz==3 && buzz==5){
                ret.add("FizzBuzz");
                fizz=0;
                buzz=0;
            }else if(fizz==3){
                ret.add("Fizz");
                fizz=0;
            }else if(buzz==5){
                ret.add("Buzz");
                buzz=0;
            }else{
                ret.add(String.valueOf(i));
            }
        } 
        return ret;
    }
}

 

附加: 

ArrayList和LinkedList的大致区别如下:
1.ArrayList是实现了基于动态数组的数据结构,LinkedList基于链表的数据结构。 
2.对于随机访问get和set,ArrayList觉得优于LinkedList,因为LinkedList要移动指针。 
3.对于新增和删除操作add和remove,LinedList比较占优势,因为ArrayList要移动数据。

原文地址:https://www.cnblogs.com/lcbg/p/6575401.html