zoukankan      html  css  js  c++  java
  • 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”.

    Example:

    n = 15,
    
    Return:
    [
        "1",
        "2",
        "Fizz",
        "4",
        "Buzz",
        "Fizz",
        "7",
        "8",
        "Fizz",
        "Buzz",
        "11",
        "Fizz",
        "13",
        "14",
        "FizzBuzz"
    ]
    

    ##分析 遍历1~n的所有整数并以字符串形式存入List中,3的倍数"Fizz",5的倍数"Buzz",15的倍数"FizzBuzz"
    ##解答 ###解法1:(我)(3ms√) ``` public class Solution { public List fizzBuzz(int n) { List list = new ArrayList(); for (int i = 1; i <= n; i++) { if (i % 15 == 0) { list.add("FizzBuzz"); } else if (i % 3 == 0) { list.add("Fizz"); } else if (i % 5 == 0) { list.add("Buzz"); }
            else{
                list.add(Integer.toString(i));//或String.valueOf(i)
            }
        }
        return list;
    
    }
    

    }

     <br />
    ###解法2:不用"%"操作符<font  color=blue>(4ms)</font>
    
    Integer.highestOneBit() 返回一个int值:如果i具有'1'位,则返回值具有1个'1'位,其位置即是i的最高位(最左边)的'1'位的位置;如果i不具有'1'位,则i=0,返回0。例:Integer.highestOneBit(5) = 4,因为5的二进制表示为101,返回值的二进制表示为100
    
    

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

  • 相关阅读:
    fastDFS同步问题讨论
    Android开发(26)--补间动画(Tween)的实现
    android布局
    Linux特殊权限:SUID、SGID、SBIT
    如何使用ssh-keygen生成key
    Linux中环境变量到底写在哪个文件中?解析login shell 和 no-login shell
    使用ssh无密码登录
    github中的ssh配置
    PHP中的一个很好用的文件上传类
    [置顶] js模板方法的思路及实现
  • 原文地址:https://www.cnblogs.com/xuehaoyue/p/6412534.html
Copyright © 2011-2022 走看看