Solved: 12 - Recursion
This commit is contained in:
@@ -2,8 +2,35 @@
|
|||||||
|
|
||||||
namespace functions {
|
namespace functions {
|
||||||
|
|
||||||
auto fibonacci(int n) -> long long { (void)n; return 0; }
|
auto fibonacci(const int n) -> long long {
|
||||||
auto sum_digits(int n) -> int { (void)n; return 0; }
|
if (n == 0) return 0;
|
||||||
auto is_palindrome(int n) -> bool { (void)n; return false; }
|
if (n == 1) return 1;
|
||||||
|
return fibonacci(n - 1) + fibonacci(n - 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
auto sum_digits(const int n) -> int {
|
||||||
|
if (n < 10) return n;
|
||||||
|
return n % 10 + sum_digits(n / 10);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Advanced recursion with recursive lambda helper
|
||||||
|
auto is_palindrome(const int n) -> bool {
|
||||||
|
auto f = [](const auto& self, const int x, const int d) -> bool {
|
||||||
|
if (x < 0) return false;
|
||||||
|
if (x < 10) return true;
|
||||||
|
if (x / d != x % 10) return false;
|
||||||
|
if (d < 10) return true;
|
||||||
|
const int m = (x / d) / 10;
|
||||||
|
return self(self, m, d / 100);
|
||||||
|
};
|
||||||
|
if (n < 0) return false;
|
||||||
|
if (n < 10) return true;
|
||||||
|
int d = 1;
|
||||||
|
while (n / d >= 10) {
|
||||||
|
d *= 10;
|
||||||
|
}
|
||||||
|
return f(f, n, d);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
} // namespace functions
|
} // namespace functions
|
||||||
|
|||||||
Reference in New Issue
Block a user