Finding reverse of a number
METHOD 1:
#include<stdio.h>
/* Iterative function to reverse digits of num*/
int reversDigits(int num)
{
int rev_num = 0;
while(num > 0)
{
rev_num = rev_num*10 + num%10;
num = num/10;
}
return rev_num;
}
int main()
{
int num = 4562;
printf("Reverse of no. is %d", reversDigits(num));
getchar();
return 0;
}
OUTPUT:
Reverse of no. is 2654
Time complexity: O(log(n)) where n is the input number.
The above program gives the output 1 for an input 100. To get the output as 001, a small addition is done in the above program.
int reversDigits(int num)
{
int rev_num = 0,zero=0;
while(num>0)
{
if(num%10==0)
{
zero++;
num=num/10;
}
else break;
}
while(num > 0)
{
rev_num = rev_num*10 + num%10;
num = num/10;
}
return rev_num;
}
METHOD 2:
#include <stdio.h>
#include <conio.h>
int main()
{
char a[5]; //Get the number as a string
int n;
printf("enter a number\n");
scanf("%s",a);
strrev(a); //reverse the string using strrev() function
n=atoi(a); //convert string to integer
printf("%d",n);
getch();
return 0;
}
OUTPUT:
enter a number
1234
4321
METHOD 1:
#include<stdio.h>
/* Iterative function to reverse digits of num*/
int reversDigits(int num)
{
int rev_num = 0;
while(num > 0)
{
rev_num = rev_num*10 + num%10;
num = num/10;
}
return rev_num;
}
int main()
{
int num = 4562;
printf("Reverse of no. is %d", reversDigits(num));
getchar();
return 0;
}
OUTPUT:
Reverse of no. is 2654
Time complexity: O(log(n)) where n is the input number.
The above program gives the output 1 for an input 100. To get the output as 001, a small addition is done in the above program.
int reversDigits(int num)
{
int rev_num = 0,zero=0;
while(num>0)
{
if(num%10==0)
{
zero++;
num=num/10;
}
else break;
}
while(num > 0)
{
rev_num = rev_num*10 + num%10;
num = num/10;
}
return rev_num;
}
METHOD 2:
#include <stdio.h>
#include <conio.h>
int main()
{
char a[5]; //Get the number as a string
int n;
printf("enter a number\n");
scanf("%s",a);
strrev(a); //reverse the string using strrev() function
n=atoi(a); //convert string to integer
printf("%d",n);
getch();
return 0;
}
OUTPUT:
enter a number
1234
4321
No comments:
Post a Comment