+ 1
reverse function
I want to reverse this function of numbers. Its problem? #include <iostream> int varon(int x) { if (x <10) return x; else return (varon(x %10),varon(x/10)); }
3 odpowiedzi
+ 2
#include <iostream>
int reverseNumber(int x, int rev = 0) {
// Base case: If x becomes 0, return the reversed number
if (x == 0)
return rev;
// Recursive case: Add the last digit of x to rev and call the function again with x divided by 10
return reverseNumber(x / 10, rev * 10 + x % 10);
}
int main() {
int number = 1234;
int reversed = reverseNumber(number);
std::cout << "Reversed Number: " << reversed << std::endl;
return 0;
}
0
Add & for int x and see.
0
Your varon() function is missing a part where it should "remember" the reversed version of the original number, <x>, given as argument.
As it is now, the function would not work as intended when the original number was a negative number. You can check whether <x> was greater than -10 AND <x> was less than 10 (rather than only whether <x> was less than 10), to work with negative number,
Hint:
Use a static variable for temporarily storing the reversed version of the original number. Once the base case is reached, you can reset the static variable's value to zero such that the static variable's value on successive calls will always be zero, in anticipation for miscalculation.