Reputation: 1142
I know such questions have been asked before, but all of them use strings.
Most common answers to such questions are :
convert to string and take number.Length - 1
. However I don't want to use strings.
Divide by 10, but this only works for whole numbers. If I have 1.12 and I divide it by 10 I dont get 2.
Turn the number into array and then reverse it. Which is the same as using a string but more work and its not what I am looking for.
So my question is if I have input like 1.12 I want 21.1 but without using any strings. I want to take the 2 and save it as a number and then take the rest and add the dot.
I want a mathematical solution to the problem.
I will provide you with some test cases so you better understand my problem.
23.45 => 54.32
0.50 => 05.0 => 5
4.3445242 => 2425443.4
232 => 232
123 => 321
And I dont want strings or arrays because when you say "I dont want strings" there is always someone who says " turn the number into array and then reverse it". Nah... I want to use only calculations, if-else and cycles (for,while,do while)
Upvotes: 1
Views: 1056
Reputation: 630
A relatively ugly way would be essentially promote that double into long and remember the decimal point. Then reverse the long, then divide it by total number of digits minus originl decimal point. Also, if you want to handle negative numbers, you would have to store the sign and Math.Abs the src double you start mucking around with it.
private double Reverse(double src)
{
double dst = 0;
int decPoint = 0;
while (src - (long)src > 0)
{
src = src * 10;
decPoint++;
}
int totalDigits = 0;
while (src > 0)
{
int d = (int)src % 10;
dst = dst * 10 + d;
src = (long)(src / 10);
totalDigits++;
}
if (decPoint > 0)
{
int reversedDecPoint = totalDigits - decPoint;
for (int i = 0; i < reversedDecPoint; i++) dst = dst / 10;
}
return dst;
}
Upvotes: 1