diff options
Finished counting and powerof2
1 files changed, 20 insertions, 21 deletions
| -rw-r--r-- | Year 1/Object-oriented Programming/05-Practice-22.03.2022.cpp | 41 |
diff --git a/Year 1/Object-oriented Programming/05-Practice-22.03.2022.cpp b/Year 1/Object-oriented Programming/05-Practice-22.03.2022.cpp index 02600bf..ef09940 100644 --- a/Year 1/Object-oriented Programming/05-Practice-22.03.2022.cpp +++ b/Year 1/Object-oriented Programming/05-Practice-22.03.2022.cpp @@ -151,14 +151,16 @@ void ex2() { // Exercise 3 bool isPowerOf2(int x) { - int buff = true; + bool oneOccured = false; while (x != 0) { - if (x & 1) buff = false; - x >>= 1; + if (x % 2 == 1 && oneOccured) + return false; + if(x % 2 == 1) + oneOccured = true; - res = !res; + x /= 2; } - return res; + return true; } bool isPalindrome(int num) { @@ -186,6 +188,15 @@ class Interval { int b; bool edgesPowersOf2; + int counter(bool (comparator)(int)) const { + int count = 0; + for (int i = a; i <= b; i++) { + if (comparator(i)) + count++; + } + return count; + } + public: Interval(); Interval(int a, int b); @@ -196,7 +207,7 @@ class Interval { int getLen() const; bool isInInterval(int x) const; - int countOfWholeNumbers() const; + int primeNumbersCount() const; int palindromesCount() const; int numsNonRepeatingDigitsCount() const; @@ -229,26 +240,14 @@ bool Interval::isInInterval(int x) const { return a >= x && x <= b; } -int Interval::countOfWholeNumbers() const { - return this->b - this->a; -} + int Interval::palindromesCount() const { - int count = 0; - for (int i = a; i <= b; i++) { - if (isPalindrome(i)) - count++; - } - return count; + return this->counter(isPalindrome); } int Interval::numsNonRepeatingDigitsCount() const { - int count = 0; - for (int i = 0; i <= b; i++) { - if (hasRepeatingDigits(i)) - count++; - } - return count; + return this->counter(hasRepeatingDigits); } int Interval::endBegArePowersOf2() const { |
