Most programmers cant solve this.

This is the fabled Fizzbuzz problem, which is said that most programmers cant solve in longhand. Its a common question asked in programming interviews.

Write a program that prints the numbers from 1 to 100. But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”.

Please post your solution or a link to your solution in whatever language you are most comfortable in and also how long it took you to solve it. Please try not to google it first before trying to solve it

Advertisements

8 thoughts on “Most programmers cant solve this.

  1. “<?php
    /**This should do the trick::PUMBA*/
    $min = 1;
    $max = 100;
    for( $x=$min; $x<=$max; $x++ ){
    if( ($x%5 == 0) && ($x%3 == 0 ) ){
    //fizzbuzz
    $num = "FizzBuzz";
    }else if( ($x%3 == 0) && ($x%5 != 0 ) ){
    //multiple of 3 only
    $num = "Fizz";

    }else if( ($x%3 != 0) && ($x%5 == 0 ) ){
    //multiple of 5 only
    $num = "Buzz";
    }else{
    //Number straight
    $num = $x;
    }
    echo "&nbsp $num “;
    }
    ?>”

  2. perl -e ‘for my $num ( 1 .. 100 ) { my $out; ( $num % 3 ) or $out = “Fizz”; ( $num % 5 ) or $out .= “Buzz”; print $out || $num, “\n”;}’

  3. public class FizzBuzz {
    public static void main(String[] args)
    {
    for(i=0; i 0 && i % 3 == 0 && i % 5 == 0)
    System.out.println(“FizzBuzz”);
    else if(i > 0 && i % 3 == 0)
    System.out.println(“Fizz”);
    else if(i > 0 && i % 5 == 0)
    System.out.println(“Buzz”);
    else
    System.out.println(i);

    }
    }
    }

  4. #This is my solution in python

    for number in xrange(1, 101):
    if (number%3 == 0) and (number%5 == 0):
    print “FizzBuzz”
    elif number%3 == 0:
    print “Fizz”
    elif number%5 == 0:
    print “Buzz”
    else:
    print number

  5. Solutions in python
    (1) By list comprehension:

    output = [ ‘fizzbuzz’ if num % 3 == 0 and num % 5 == 0 else ‘fizz’ if num % 3 == 0 else ‘buzz’ if num % 5 == 0 else num for num in range(1,101)]

    print output

    (2)
    for num in range(1, 101):
    if num % 3 == 0:
    print ‘Fizz’,
    if num % 5 == 0:
    print ‘Buzz’,
    if num % 3 != 0 and num % 5 != 0:
    print num,
    print ‘\n’

    The second solution i think, is readable, natural and quite easy to comprehend; while the first is more compact

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s