I have this recursive function to reverse a positive integer. Anybody having an efficient algorithm to do the task using fewer recursive calls (but still using recursion), please post here!
int countDigit (const int & _X) {
if (_X < 10)
return 1;
return (countDigit(_X / 10) + 1);
}
int getPower (const int & _X, const int & _Y) {
if (_Y == 0)
return 1;
int ans = getPower(_X, _Y / 2);
if (_Y % 2)
return _X * ans * ans;
return ans * ans;
}
int reverseDigit (const int & digit) {
if (digit < 10) {
return digit;
}
int num = (digit % 10) * getPower(10, countDigit(digit / 10));
return num + reverseDigit(digit / 10);
}
Sure ... effectively read in digits from the number and add them to the end of a temporary number:
EDIT: Based on the questioner's bizarre modification of the question (to require recursion), I have edited my clean iterative solution to include an arbitrary amount of recursion, denoted by the positive integer [recurse].
int reverseDigit(int digit, int recurse=1) {
if (recurse>0) reverseDigit(digit,recurse-1);
int num=0;
while (digit!=0) {
num*=10;
num+=digit%10;
digit/=10;
}
return num;
}
This is recursive
void reverse(int number, int& result)
{
if (number == 0) return;
else
{
result *= 10;
result += number % 10;
reverse(number / 10, result );
}
}
This is how you call it with (545146548) example
void main()
{
int result = 0;
reverse(545146548, result);
cout << result << endl;
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.