From e6bdb3bdd84deddf09678a3ce88f19fe1c90aaf4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?David=20Gil=20de=20G=C3=B3mez=20P=C3=A9rez?= Date: Wed, 12 Aug 2026 17:30:55 +0300 Subject: [PATCH] Solved: 12 - Recursion --- modules/03_functions/src/recursion.cpp | 33 +++++++++++++++++++++++--- 1 file changed, 30 insertions(+), 3 deletions(-) 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