Java > Logic-1 > fizzString2 (CodingBat Solution)

Problem:

Given an int n, return the string form of the number followed by "!". So the int 6 yields "6!". Except if the number is divisible by 3 use "Fizz" instead of the number, and if the number is divisible by 5 use "Buzz", and if divisible by both 3 and 5, use "FizzBuzz". Note: the % "mod" operator computes the remainder after division, so 23 % 10 yields 3. What will the remainder be when one number divides evenly into another? (See also: FizzBuzz Code and Introduction to Mod)

fizzString2(1) → "1!"
fizzString2(2) → "2!"
fizzString2(3) → "Fizz!"


Solution:

public String fizzString2(int n) {
    boolean fizz = n % 3 == 0;
    boolean buzz = n % 5 == 0;
 
    if (fizz && buzz) return "FizzBuzz!";
    if (fizz) return "Fizz!";
    if (buzz) return "Buzz!";
    return n + "!";
}

5 comments:

  1. Bad Idea.
    Your solution, is not suitable for change requirement.
    What if you need to include divisible by 7 with a different word.
    You need to change maximum lines.
    Try a solution, where you need only one change, if there is one additional requirement.

    ReplyDelete
  2. public String fizzString2(int n) {
    if(n%3==0 && n%5==0)
    return "FizzBuzz!";
    if(n%3==0)
    return "Fizz!";
    if(n%5==0)
    return "Buzz!";
    return n+"!";
    }

    ReplyDelete
  3. private final String fizzString2(int fizzString) {

    if(fizzString % 3 == 0){
    if(fizzString % 5 == 0){
    return "FizzBuzz!";
    }
    return "Fizz!";
    }
    if(fizzString % 5 == 0){
    return "Buzz!";
    }
    return Integer.toString(fizzString) + "!";
    }

    ReplyDelete
  4. if(n%5==0&&n%3==0)return "FizzBuzz!";
    else if(n%5==0&&n%3!=0) return "Buzz!";
    else if(n%5!=0&& n%3==0) return "Fizz!";
    else return n+"!";

    ReplyDelete
  5. String newStr = "" ;
    if (n % 3 != 0 && n % 5 != 0) return n + "!" ;
    if ( n % 3 == 0) newStr = newStr + "Fizz" ;
    if (n % 5 == 0) newStr = newStr + "Buzz" ;
    return newStr + "!" ;

    ReplyDelete