Saturday, January 7, 2012

Reverse digits of a number / Palindromic Number or not

Write an optimal C program to reverse digits of a number.Also check whether the number is palindromic or NOT

Iterative Way:
//4562 ->2654
int reversDigits(int num)
{
int rev_num = 0;
while(num > 0)
{
rev_num = rev_num*10 + num%10;
num = num/10;
}
return rev_num;
}

Time Complexity: O(Log(n)) where n is the input number.

Recursive way:-
int reversDigits(int num)
{
static int rev_num = 0;
static int base_pos = 1;
if(num > 0)
{
reversDigits(num/10);
rev_num += (num%10)*base_pos;
base_pos *= 10;
}
return rev_num;
}

Time Complexity: O(Log(n)) where n is the input number
Note that above above program doesn’t consider leading zeroes. For example, for 100 program will print 1.

For printing Trailing Zeros:-------------

#include<stdio.h>
 
void reversDigits(unsigned int num)
{
  int rev_num = 0,zeros=0;
  while(num >0)
  {
    /*count trailing zeroes,
     i.e., for 100 zeros will be 2*/       
    if(num%10==0)
    {  
      zeros++;
      num = num/10;
    }
    else break;
  }
 
  /* Get the reverse number */
  while(num > 0)
  {
    rev_num = rev_num*10 + num%10 ;
    num = num/10;
  }
   
  /* print leading zeroes in reverse number */
  while(zeros--)
    printf("0");
 
  /* print reverse number */
  printf("%d\n",rev_num);
}
 
int main()
{
  unsigned int x = 100;
  reversDigits(x);
  getchar();
}

No comments:

Post a Comment