1. 程式人生 > >每日一題(C語言基礎篇)2

每日一題(C語言基礎篇)2

題目描述:使用C語言將一個整型數字轉換成字串並倒序列印,例如:123轉換成字串321,-1234轉換成字串-4321。

程式碼實現:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* 將一個整型數字轉換成字串並倒序列印 */


void Recur(int num);
char * Recur1(int num);


int main(void)
{
	char * str;

	str = Recur1(-12345);
	printf("%s\n", str);
	Recur(12345
); } /* 遞迴 */ void Recur(int num) { if(num == 0) { printf("\n"); return; } if(num < 0) { num = -num; printf("%c", '-'); } printf("%c", (num % 10) + '0'); Recur(num/10); } /* 不使用遞迴且返回指標 */ char * Recur1(int num) { char * temp; int num_bak = num; int i; int len; char value; temp = (
char *)malloc(10); if(num == 0) { temp[0] = '0'; return temp; } if(num < 0) num = -num; for(i = 0; num != 0; i++) { temp[i] = num % 10 + '0'; num = num / 10; } len = i; for(int j = len - 1; j >= 0; j--) { temp[j + 1] = temp[j]; } temp[len + 1] = '\0'; temp[0] = '-'; return temp; }

思考邏輯:
(1) 整數為0時,需返回字串0;
(2) 不為0時,對整數以10取餘,可得到最後一位數;
(3) 對整數除10可去除整數的個位數;

注意:負數需要考慮到陣列的移位操作。