C/C++中有函數itoa()來實作int型與字元串的轉換,我們也可以使用整數加‘0’的方法,整數加‘0’會隐式地轉換成char類型。如有需要,請通路我的Github擷取包含測試程式的C++源碼。
1、使用itoa()函數的實作如下:
class Solution
{
public:
void my_itoa(int x)
{
char str[];
//函數的三個參數:第一個為要轉換的int型整數,第二個為存放字元串的char變量,第三個是10進制轉換
itoa(x, str,);
cout << str << endl;
}
};
2、使用整數加‘0’的方法實作如下:
class Solution
{
public:
void my_itoa(int x)
{
//定義臨時變量temp
int temp = x;
//若int型值為負數,用它的絕對值轉換,然後再加符号
if(x < )
{
temp = -x;
}
char ch[] = "";
int i = ;
while(temp)
{
//char類型和int類型的轉換關系
ch[i] = (temp % ) + '0';
temp = temp / ;
i++;
}
//若int型整數為負數,則char類型的長度要增加1來存放符号
int len;
if(x < )
{
len = i + ;
i++;
}
else
{
len = i;
}
char str[];
//最後一個字元存放NUL
str[i] = ;
while()
{
i--;
//目前字元為空,結束循環
if(ch[len - i - ] == )
{
break;
}
str[i] = ch[len - i - ];
}
if(i == )
{
str[i] = '-';
}
cout << str << endl;
}
};