Friday, 26 September 2014

Reverse Integer

This Is one of Very Basic Programming Problem  for beginner . But If you never Did it , Try it once.

Reverse Given Number :- 

Example >> Let Number is 12345 then after reversing Number Should be 54321

There is two way to do it

Way 1:-

Pop Last Digit then push it to another variable and repeat procedure until       number == 0
  • temp = num%10
  • num = num/10
  • numr = numr*10 + temp
  • repeat above step until num==0

C++ Program to Reverse integer :

  1. // Reverse a Number
  2. //Ex:- 12345 -> 54321
  3. #include<iostream>
  4. using namespace std;
  5. main(){
  6.         long int num,numr=0;
  7.         int temp;
  8.         cout<<"Enter Number : ";
  9.         cin>>num;
  10.         // Reverse Number :- just pop last digit and push it to numr,
  11.         //repeate above step untill num=0
  12.         while(num>0){
  13.                 temp=num%10;
  14.                 num =num/10;
  15.                 numr=(numr*10)+temp;
  16.         }
  17.         cout<<"Revrsed number :"<<numr;
  18.         return 0;
  19. }

Way 2 :-

Convert number In string then reverse it than change it to integer . In some programming language it is very easy .

Python :- Reverse Integer :-

  1. # Reverse an interger
  2. if __name__=='__main__':
  3.     num=int(raw_input('Enter Number: '))
  4.     numr=str(num)[::-1] #reverse String
  5.     numr=int(numr)
  6.     print 'reverse integer :',numr

OutPut :-

Reverse Integer

No comments:

Post a Comment

THANKS FOR UR GREAT COMMENT

Blogger Widgets