diff --git a/modules/03_functions/src/recursion.cpp b/modules/03_functions/src/recursion.cpp index 8e3bee4..052db9a 100644 --- a/modules/03_functions/src/recursion.cpp +++ b/modules/03_functions/src/recursion.cpp @@ -2,8 +2,35 @@ namespace functions { -auto fibonacci(int n) -> long long { (void)n; return 0; } -auto sum_digits(int n) -> int { (void)n; return 0; } -auto is_palindrome(int n) -> bool { (void)n; return false; } +auto fibonacci(const int n) -> long long { + if (n == 0) return 0; + 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