Bloomberg LP Interview Question
Financial Software Developershey wat if i take num=0321. Then it shud convert it to 1230.
i tried my code but it is not converting the number to 1230.
and same problem i found with ur code.
yeah.. true . But i have problem like if you reverse a number 2 times then we should get the same number.
But problem comes in case like this:
number=1230 reversed into =>0321 and if u reverse it again then we should get number=>1230.
You are correct, any integer reversed twice should be equal to its original value. The reason you are experiencing all these problems is because you are reversing characters of a corresponding string representation of an integer, instead of reversing bits of that integer. If you look at binary representation of 2 (00000010) and truly reverse it to 01000000, you will arrive to decimal 64. Then, if you reverse 64 (01000000) back to 00000010, you will have your decimal 2 back.
int reverseDigits(int digit)
{
int isNegative = 0;
if(digit<0) {
isNegative =1;
digit*=-1;
}
if(digit==0) return 0;
int reverse=0;
while(digit){
reverse*=10;
reverse += digit%10;
digit/=10;
}
return isNegative==0? reverse:reverse*-1;
}
How about this:
Let N = 2350.
while(N)
{
int x = N%10;
push(S, x); //push x into a stack S.
N /= 10;
k++ ; //keeps track of length of N
}
//now do pop operation
while(k--)
{
printf( "%d", pop(S));
}
I assume by reverse, you mean the following:
- B January 01, 2010123=>321
-123=>-321
+123=>+321
If the input is 'string', you might need some string manipulation.
Trim any extra spaces,commas etc.
Parse the leftmost char, if it's +/-, preserve it some stack.
Then try the following algo.
newnum=0;
while(num)
{
i=num%10;
if(newnum==0)
{
newnum=i;
}
else
{
newnum=newnum*10+i;
}
num=num/10;
}
return newnum;