Java Solution with 3 if conditions


  • 4
    P
    public List<String> fizzBuzz(int n) {
            
            List<String> ls = new ArrayList<String>();
            StringBuffer sb = new StringBuffer();
            for(int i=1;i<=n;i++){
                sb.setLength(0);
                if(i%3==0){
                    sb.append("Fizz");
                }
                if(i%5==0){
                    sb.append("Buzz");
                }
                if(sb.length()==0){
                    sb.append(String.valueOf(i));
                }
                ls.add(sb.toString());
            }
            return ls;
        }
    

  • 2

    is it really worth the StringBuilder rather than just use 4 distinct case? Thoughts? Thanks.


  • 1
    S

    Same question, why do we need StringBuffer here?


  • 0
    X

    This method is good also, use an empty string to determine whether I think will be better. Back to the second floor, StringBuffer and StringBuilder is actually same, the difference between just StringBuilder than StringBuffer thread safety.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.