FizzBuzz

I ran into the FizzBuzz challenge at HackerRank (https://www.hackerrank.com/challenges/fizzbuzz?h_r=internal-search).

If you are interested take a look at the specified URL.

It was interesting the following statement:  Write a solution (or reduce an existing one) so it has as few characters as possible.

It seems to me that the practice of writing cryptic code should not be encouraged. That code needs to be maintained and in most cases modified. That said, given specific requirements, if needed very compact but efficient and well documented code is required in some cases.

The challenge did not provide sample input (non-existent) and the output was well described so there was no need for sample output.

The console output from the Eclipse IDE generated by my solution follows:

1

2

Fizz

4

Buzz

Fizz

7

8

Fizz

Buzz

11

Fizz

13

14

FizzBuzz

16

17

Fizz

19

Buzz

Fizz

22

23

Fizz

Buzz

26

Fizz

28

29

FizzBuzz

31

32

Fizz

34

Buzz

Fizz

37

38

Fizz

Buzz

41

Fizz

43

44

FizzBuzz

46

47

Fizz

49

Buzz

Fizz

52

53

Fizz

Buzz

56

Fizz

58

59

FizzBuzz

61

62

Fizz

64

Buzz

Fizz

67

68

Fizz

Buzz

71

Fizz

73

74

FizzBuzz

76

77

Fizz

79

Buzz

Fizz

82

83

Fizz

Buzz

86

Fizz

88

89

FizzBuzz

91

92

Fizz

94

Buzz

Fizz

97

98

Fizz

Buzz

The following Java code passed the single test case:

public class Solution {

public static void main(String[] args) {

// **** second attempt (passed) ****

String s = “”;

for (int i = 1; i <= 100; i++) {

if (((i % 3) == 0) && ((i % 5) == 0)) {

s = “FizzBuzz”;

}

if (((i % 3) == 0) && ((i % 5) != 0)) {

s = “Fizz”;

}

if (((i % 3) != 0) && ((i % 5) == 0)) {

s = “Buzz”;

}

if (((i % 3) != 0) && ((i % 5) != 0)) {

s = Integer.toString(i);

}

System.out.println(s);

// **** first attempt (passed) ****

//                   if (((i % 3) == 0) && ((i % 5) == 0)) {

//                         System.out.println(“FizzBuzz”);

//                   }

//                   if (((i % 3) == 0) && ((i % 5) != 0)) {

//                         System.out.println(“Fizz“);

//                   }

//                   if (((i % 3) != 0) && ((i % 5) == 0)) {

//                         System.out.println(“Buzz”);

//                   }

//                   if (((i % 3) != 0) && ((i % 5) != 0)) {

//                         System.out.println(i);

//                   }

}

}

}

If you have comments or questions regarding this or any other entry in this blog, please do not hesitate and send me a message. Will reply as soon as possible and will not use your name unless you explicitly allow me to do so.

John

john.canessa@gmail.com

Follow me on Twitter: @john_canessa

 

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.