Advertisement
OpenSourcePhilosiphe

An Elegant Fizzbuzz

Mar 13th, 2018
166
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.69 KB | None | 0 0
  1. //fizzbuzz without mod, multiplication, division, or subtraction:
  2. #include <iostream>
  3. #include <iomanip>
  4.  
  5. //constant for 15 bitshifts AKA binary => 1000 0000 0000 0000 (16 digits over)
  6. #define FIZZBUZZ 32768
  7.  
  8. //constant for 5 bitshifts AKA binary => 0010 0000 (6 digits over)
  9. #define BUZZ 16
  10.  
  11. //constant for 3 bitshifts AKA binary => 1000 (4 digits over)
  12. #define FIZZ 8
  13.  
  14.  
  15. int main()
  16. {
  17.     //create your tracking variables prepped for bitshift
  18.     short unsigned int fizzBuzzTracker = 1, buzzTracker = 1, fizzTracker = 1;
  19.  
  20.     //loop for 1000 itterations of fizzbuzz
  21.     for (unsigned int i=0; i <= 1000;i++)
  22.     {
  23.         if (fizzBuzzTracker == FIZZBUZZ)//do this if we reached a fizzbuzz(iteration is divisible by 15, (i % 15) == 0)
  24.         {
  25.             std::cout << "Fizzbuzz!";//output fizzbuzz
  26.             fizzBuzzTracker = buzzTracker = fizzTracker = 1;//reset all tracking varables
  27.         }
  28.         else if (buzzTracker == BUZZ)//do this if we reached a buzz(iteration is divisible by 5, (i % 5) == 0)
  29.         {
  30.             std::cout << "Buzz!";//output buzz
  31.             buzzTracker = 1;//reset the buzz tracker variable
  32.         }
  33.         else if (fizzTracker == FIZZ)//do this if we reached a fizz(iteration is divisible by 3, (i % 3) == 0)
  34.         {
  35.             std::cout << "Fizz!";//output fizz
  36.             fizzTracker = 1;//reset the fizz tracker variable
  37.         }
  38.         else//no special conditions were hit
  39.         {
  40.             //output the current iteration number
  41.             std::cout << i;
  42.         }
  43.  
  44.         std::cout << std::endl;//go to the next line
  45.  
  46.         //bitshift the tracker variables
  47.         fizzBuzzTracker = fizzBuzzTracker << 1;
  48.         buzzTracker = buzzTracker << 1;
  49.         fizzTracker = fizzTracker << 1;
  50.  
  51.     }//end fizzbuzz for()
  52.  
  53.     std::cin.get();//pause
  54.  
  55.     return 0;
  56. }
  57.  
  58.  
  59. //alternate FizzBuzz: https://pastebin.com/XnZwE4DN
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement