Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
oorrja
GitHub Repository: oorrja/learntosolveit
Path: blob/master/languages/cprogs/Ex_3.4_itoa-2.c
1240 views
1
/* Modified version of itoa; to handle the situation of MIN_INT of limits.h
2
in the previous number = -2147483648 would fail at n =-n,because the max value of integer is 2147483647
3
4
modifying itoa to handle these situations.
5
sign is stored as the number itself, absolute value of each digit is stored in the string and
6
while loop is tested not for 0
7
8
itoa: convert an integer to string */
9
10
#include<stdio.h>
11
#include<string.h>
12
#define MAXLINE 1000
13
14
#define abs(x) ( (x) > 0 ? (x): -(x))
15
16
void itoa(int n,char s[]);
17
void reverse(char s[]);
18
19
20
int main(void)
21
{
22
int number;
23
char str[MAXLINE];
24
25
/* number=-2345645; */
26
27
number = -2147483648;
28
29
30
printf("Integer %d printed as\n String:",number);
31
32
itoa(number,str);
33
34
printf("%s",str);
35
36
return 0;
37
}
38
39
void itoa(int n,char s[])
40
{
41
int i,sign;
42
43
sign=n;
44
45
i = 0;
46
47
do
48
{
49
s[i++]= abs(n%10) + '0';
50
51
}while((n/=10)!=0);
52
53
if( sign < 0)
54
s[i++]='-';
55
56
s[i]='\0';
57
58
reverse(s);
59
}
60
61
void reverse(char s[])
62
{
63
int c,i,j;
64
65
for(i=0,j=strlen(s)-1;i<j;i++,j--)
66
c=s[i],s[i]=s[j],s[j]=c;
67
}
68
69
70