1. it does not handle negative integer
2. it does not handle integer zero
Cong Wang's solution
==============================================
void GetInt(char *strint, int val){
char rev[100];
int length=0;
while (val > 0)
{
int a = val % 10;
rev[length++] = a | '0';
val /= 10;
}
rev[length]='\0';
length--;
int rev = 0;
while (length >= 0)
{
strint[rev++] = rev[length--];
}
strint[rev] = '\0';
}
==============================================
my new solution
==============================================
void GetInt(char *strint, int val) {
int len = 0;
bool negative = false;
if(val < 0) { // if negative
val = -val;
negative = true;
} else if (val == 0) { // if 0
strint[len++] = '0';
}
while (val > 0) {
strint[len++] = (val % 10) + '0';
val /= 10;
}
if(negative) {
strint[len++] = '-';
}
// reverse this string
for(int i=0; i < len /2; i++) {
char a = strint[i];
strint[i] = strint[len-1-i];
strint[len-1-i] = a;
}
strint[len] = '\0';
}
No comments:
Post a Comment