zoukankan      html  css  js  c++  java
  • 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要移动数据。

  • 相关阅读:
    Scanner类
    每日总结-05-17
    栈的基本操作 出栈与入栈
    Angularjs1.x 项目结构
    【树形dp小练】HDU1520 HDU2196 HDU1561 HDU3534
    [ACM] hdu 1251 统计难题 (字典树)
    Asakura的魔法世界
    distcp导致个别datanode节点数据存储严重不均衡分析
    Redis集群主备模式部署
    java的输入输出流(一)
  • 原文地址:https://www.cnblogs.com/lcbg/p/6575401.html
Copyright © 2011-2022 走看看