4
kira
7y

Reverse number(logic)
------
First Approach :=
void reverseMethod(int n)
{
String str="";
int temp=0;
while(n>0)
{
temp=n%10;
n=n/10;
str=str+""+temp;
}
System.out.println(str);
}
-----
Second Approach :=
void reverseMethod(int n)
{
int temp=0;
int rev=0;
while(n>0)
{
temp=n%10;
n=n/10;
rev=rev*10+temp;
}
System.out.println(rev);
}
-----

why the fuck second one is recommended??
In first, at least we do not required to remember that formula.

Comments
  • 2
    Coz 2nd one is easier for teachers and there is no type conversion. Say you want to check for palindrome after an number reversal you have to convert them to a same type.

    This is an assumption I also don't know the real reason for that.
  • 0
    @over9000 same palindrome reason mentioned by our mentor. But still we can check whether it is palindrome or not by strcomp method of String.
  • 1
    Wouldn't trailing zeros get lost with the 2nd approach?
  • 1
    @SPie a no. With trailing zeroes will never be a palindrome. Try passing 01210 in an int variable, it will store 1210 which will not be palindrome
  • 1
    @SPie Oh, but the question was for reverse, then yeah, a string variable will be needed to store zeroes and the no.s and.... well the second option will be messier and probably a wrong approach.
  • 0
    @SPie @chaostools i was not considered started with 0. That's clever, so if we consider this situation then I must go with first only.
  • 0
    what if you need to do some operations on the reverse number?
  • 0
    @sagya

    well it is based on ur requirement..

    second one has better performance than first..
  • 0
    @Akash-Jagdale in the sense of?
Add Comment