-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfizz_buzz.cpp
40 lines (36 loc) · 1.61 KB
/
fizz_buzz.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include "fizz_buzz.hpp"
FizzBuzzResult _FizzBuzzer::fizzBuzz(const unsigned long long int number) {
FizzBuzzResult cacheLookupResult = this->cache[number]; // Performance of an std::unordered_map lookup: O(1)
if (cacheLookupResult != FizzBuzzResult::UNKNOWN) return cacheLookupResult;
// Performance of an actual calculation:
FizzBuzzResult calculatedResult = FizzBuzzResult::NONE;
if (number % 15 == 0) { // O(1)
calculatedResult = FizzBuzzResult::FIZZBUZZ;
}
else if (number % 5 == 0) { // O(1)
calculatedResult = FizzBuzzResult::BUZZ;
}
else if (number % 3 == 0) { // O(1)
calculatedResult = FizzBuzzResult::FIZZ;
}
this->cache[number] = calculatedResult;
return calculatedResult;
}
FizzBuzzResult operator|(FizzBuzzResult lhs, FizzBuzzResult rhs) {
return static_cast<FizzBuzzResult>(
static_cast<std::underlying_type<FizzBuzzResult>::type>(lhs) |
static_cast<std::underlying_type<FizzBuzzResult>::type>(rhs)
);
}
FizzBuzzResult operator&(FizzBuzzResult lhs, FizzBuzzResult rhs) {
return static_cast<FizzBuzzResult>(
static_cast<std::underlying_type<FizzBuzzResult>::type>(lhs) &
static_cast<std::underlying_type<FizzBuzzResult>::type>(rhs)
);
}
tostringstream& operator<<(tostringstream& ostream, FizzBuzzResult const& fizzBuzzResult) {
if ((fizzBuzzResult & FizzBuzzResult::FIZZ) != FizzBuzzResult::UNKNOWN) ostream << TEXT("Fizz");
if ((fizzBuzzResult & FizzBuzzResult::BUZZ) != FizzBuzzResult::UNKNOWN) ostream << TEXT("Buzz");
// if ((fizzBuzzResult & FizzBuzzResult::FIZZ) != FizzBuzzResult::UNKNOWN) ostream << ostream.str().substr(0, ostream.str().find_first_of(TEXT(':')));
return ostream;
}