if statements

Raindrops
Raindrops in Java
class RaindropConverter {
    String convert(int number) {
        StringBuilder stringBuilder = new StringBuilder();
        if (number % 3 == 0) {
            stringBuilder.append("Pling");
        }
        if (number % 5 == 0) {
            stringBuilder.append("Plang");
        }
        if (number % 7 == 0) {
            stringBuilder.append("Plong");
        }
        return stringBuilder.length() != 0 ? stringBuilder.toString() : Integer.toString(number);
    }
}

This approach starts be defining a StringBuilder to build the result String.

A series of if statements uses the remainder operator to check if the number is evenly divisible by 3, 5 or 7. If so, the corresponding drop String is appended by the StringBuilder.

After the if statements, a ternary operator is used to check the StringBuilder.length(). If it is not 0, then the StringBuilder.toString() method is called and its value is returned. If the length is 0, then the number is converted to a string using Integer.toString() and is returned.

The use of StringBuilder may not be as performant for so few appends, due to the time it takes to instantiate the StringBuilder. Other ways of building the result may be faster.

27th Nov 2024 · Found it useful?