Amazon | Fizz Buzz Followup
Anonymous User
1279

So the quesiton started with a standard Fizz Buzz style. Getting a number as the input,

  • If divisible by 5 or contains 5: print Fizz
  • If divisible by 7 or contains 7: print Buzz
  • If divisible by both 5 and 7, or contains 5 and is divisible by 7, or contains 7 and is divisible by 5, or contains both 5 and 7: print FizzBuzz

so the code would look like this:

  public static String partOne(int num) {
    
    boolean isDivisbaleByFive = false;
    boolean hasFive = false;
    boolean isDivisbaleBySeven = false;
    boolean hasSeven = false;
    
    isDivisbaleByFive = num % 5 == 0;
    isDivisbaleBySeven = num % 7 == 0;

    int checkNum = num;
    while(num > 0) {
      
      int lastNum = num % 10;
      
      if (lastNum == 5) {
        hasFive = true; 
      } else if (lastNum == 7) {
        hasSeven = true;
      }
      
      // if both are true, end the loop (1233333357)
      num = num / 10;      
    }
    
    if (isDivisbaleByFive && isDivisbaleBySeven || hasFive && isDivisbaleBySeven || hasSeven && isDivisbaleByFive || hasFive && hasSeven) {
      return "FizzBuzz";
    } else if (isDivisbaleByFive || hasFive) {
      return "Fizz"; 
    } else if (isDivisbaleBySeven || hasSeven) {
      return "Buzz"; 
    }
    
    return checkNum + "";
  }

The follow up though is like this: Given those rules, we will have 16 combinations:

  • Contains_Five
  • Contains_Seven
  • Divisable_Five
  • Devisable_Seven

For example we can have all the conditions true which gives us a number which contains 5, contains 7, is divisable by 5 and also divisable by 7. The question is to find the smallest numbers for all the combinations (a list of 16 numbers). I did not finish this part.

I believe what you need to do is to assign a 4 digit String which is made by 0 or 1 for each condition above. For example based on the above condtions (in-order), String "0100" means the number should contains 7, but should not contain 5, should not be divisable by 5 or 7.

Creating these strings are easy. The part I don't get is how you should get from those binary strings to actual numbrs.

Comments (2)