Reputation: 47
When I pass an odd digit number > 1 to the function, I am getting 1 less than the actual result I should be getting and the code is working perfectly fine for an even digit number, I am not able to figure out why.
int rev_number(int num){
int arr [10];
int i=0;
int j=0;
int rev_num=0;
while(num > 0){
arr[i] = num%10;
num = num/10;
i++;
}
i--;
while(i>=0){
rev_num += arr[j] * pow(10,i);
j++;
i--;
}
return rev_num;
}
Upvotes: 0
Views: 149
Reputation: 310980
All code examples of the function showed here are invalid because the function does not process valid integer 0. So I decided to show a correct function realization.:)
using System;
namespace ReverseNumberExercise
{
class Program
{
static int ReverseNumber(int x)
{
int y = 0;
do
{
long digit;
x = ( int )Math.DivRem( x, 10L, out digit );
y = y * 10 + ( int )digit;
} while ( x != 0 );
return (y);
}
static void Main()
{
while (true)
{
Console.Write("Enter an integral number: ");
string input = Console.ReadLine();
if (string.IsNullOrEmpty(input)) break;
int x;
if (!int.TryParse(input, out x))
{
Console.WriteLine("Invalid number. Try again.");
}
Console.WriteLine("Reversed number is: {0}", ReverseNumber(x));
Console.WriteLine();
}
Console.WriteLine("\nGood bye!");
}
}
}
Upvotes: -1
Reputation: 129374
Since pow
deals with floating point values, it's integer representation may get truncated, so certain values may end up being lower than expected.
A better solution is to use integer math, such as this:
while(i>=0){
rev_num *= 10;
rev_num += arr[j];
j++;
i--;
}
There are several other ways to express the same thing, and storing the values in an array isn't strictly necessary, you could just multiply the modulo value back in.
However, my favourite "reverse a number" is to read it in as a string, and then use the standard reverse function.
So, something like this:
#include <string>
#include <algorithm>
#include <iostream>
int main()
{
std::string s;
std::cin >> s;
std::reverse(s.begin(), s.end());
std::cout << s << std::endl;
}
Upvotes: 1
Reputation: 18831
You should avoid using pow
which return a double
while you only want to manipulate integers. For example, imagine if the result of arr[j] * pow(10,i)
is 753.99..., the cast would only put 753 in rev_num
! In some cases, that will work, but not always. It's a fifty-fifty chance to work.
Try replacing:
rev_num += arr[j] * pow(10,i);
to
rev_num = rev_num * 10 + arr[j];
Have you tried to round or to add .5? Does that also fix your problem?
Upvotes: 3
Reputation: 1801
How about the following simple code
int reverseNumber(int num) {
int reverse = 0;
while(num > 0) {
reverse = reverse*10 + num%10;
num = num/10;
}
return reverse;
}
Upvotes: 3