/************************************************************************
5.6面試例題:整數/字符串之間的轉換
************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#define MAX_DIGITS_INT 10
int strToInt(char str[]) {
int neg = 0;
int num = 0;
int i = 0;
if (str[0] == ‘-‘) {
neg = 1;
i++;
}
while (str[i] != ‘\0‘) {
num *= 10;
num += str[i] - ‘0‘;
i++;
}
if (neg == 1) {
num *= -1;
}
return num;
}
void intToStr(int num, char str[]) {
int i = 0, j = 0, neg = 0;
//buffer big enough for largest int, - sign and ‘\0‘
char temp[MAX_DIGITS_INT + 2];
if (num < 0) {
neg = 1;
num *= -1;
}
do {
temp[i] = ‘0‘ + (num % 10);
num /= 10;
i++;
} while(num != 0);
if (neg == 1) {
temp[i] = ‘-‘;
i++;
}
i--;
while (i >= 0) {
str[j++] = temp[i--];
}
str[j] = ‘\0‘;
}
int main() {
//printf("%d", strToInt("-0"));
char str[MAX_DIGITS_INT];
intToStr(-123, str);
printf("%s", str);
return 0;
}