Search code examples
iosobjective-cfizzbuzz

Understanding the fizz buzz in Objective C


Hi I am trying to solve a Fizz Buzz Test (with a twist) in Objective C that lists numbers (each on a new line) from 1 to 60 in sequence, except that when the number is divisible by 6 the program should instead display “Fizz” and when the number is divisible by 10 it should display “buzz”; if the number is divisible by 6 and by 10 then it should display “Fizzbuzz”.

This is my code. Could anyone please help me make it work (something that would make a code-golfer nod with approval): int i = 60; int multiplier = 0; NSMutableArray *newArray = [NSMutableArray arrayWithObjects: @1, @2, @3, @4, @5, @"Fizz", @7, @8, @9, @"buzz", @11, @"Fizz", @13, @14, @15, @16, @17, @"Fizz, @19, @"buzz", @21, @22, @23, @"Fizz", @25, @26, @27, @28, @29, @"Fizzbuzz", @31, @32, @33, @34, @35, @"Fizz", @37, @38, @39, @"buzz", @41, @"Fizz", @43, @44, @45, @46, @47, @"Fizz", @49, @"buzz", @51, @52, @53, @"Fizz", @55, @56, @57, @58, @59, "Fizzbuzz", nil];

for(int j = 1; j<=i; j++){
if([[newArray  objectAtIndex:j-1] isKindOfClass:
[NSString class]] ){
    NSLog(@"%@", [newArray  objectAtIndex:j-1]);
}
else{
    NSLog(@"%d", [[newArray  objectAtIndex:j-1] intValue]+multiplier);
}

if(j%60 == 0){
    j -= 60;
    i -= 60;
    multiplier += 60;
}

}


Solution

  • for (int i = 1; i <= 60; i++) {
        if(!(i % 6)) {
            if (!(i % 10))
                NSLog(@"Fizzbuzz");
            else
                NSLog(@"Fizz");
        }
        else if (!(i % 10))
            NSLog(@"Buzz");
        else 
            NSLog(@"%i", i);
    }
    

    No need to create an array.