-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathProgram To Reverse a Number
86 lines (75 loc) · 1.52 KB
/
Program To Reverse a Number
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
ITERATIVE WAY
Algorithm:
Input: num
(1) Initialize rev_num = 0
(2) Loop while num > 0
(a) Multiply rev_num by 10 and add remainder of num
divide by 10 to rev_num
rev_num = rev_num*10 + num%10;
(b) Divide num by 10
(3) Return rev_num
Example:
num = 4562
rev_num = 0
rev_num = rev_num *10 + num%10 = 2
num = num/10 = 456
rev_num = rev_num *10 + num%10 = 20 + 6 = 26
num = num/10 = 45
rev_num = rev_num *10 + num%10 = 260 + 5 = 265
num = num/10 = 4
rev_num = rev_num *10 + num%10 = 2650 + 4 = 2654
num = num/10 = 0
---------------------------------------------------------------------------
// C program to implement
// the above approach
#include <stdio.h>
// Iterative function to
// reverse digits of num
int reverseDigits(int num)
{
int rev_num = 0;
while (num > 0)
{
rev_num = rev_num * 10 + num % 10;
num = num / 10;
}
return rev_num;
}
// Driver code
int main()
{
int num = 4562;
printf("Reverse of no. is %d",
reverseDigits(num));
getchar();
return 0;
}
------------------------------------
RECURSIVE WAY :
------------------------------------
// C program to reverse digits
// of a number
#include <stdio.h>;
// Recursive function to
// reverse digits of num
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;
}
// Driver code
int main()
{
int num = 4562;
printf("Reverse of no. is %d",
reversDigits(num));
getchar();
return 0;
}