我是用字串處理的方式,index 從開頭和結尾分別去除連續的 0,再反向輸出字串。
// a038: 數字翻轉 #include <stdio.h> #include <string.h> int main() { char cstr[20]; int st, en; while (scanf("%s", cstr) != EOF) { st = 0, en = strlen(cstr) - 1; while (cstr[st] == '0') ++st; // 從開頭去除 0 while (cstr[en] == '0') --en; // 從結尾去除 0 if (st > en) { // 整串都是 0 的情況 puts("0"); } else { for (int i = en; i >= st; --i) printf("%c", cstr[i]); // 反向輸出 puts(""); // 換行 } } return 0; }
拿 AC (0ms, 84KB)
。
我是用字串處理的方式,index 從開頭和結尾分別去除連續的 0,再反向輸出字串。
// a038: 數字翻轉 #include #include int main() { char cstr[20]; int st, en; while (scanf("%s", cstr) != EOF) { st = 0, en = strlen(cstr) - 1; while (cstr[st] == '0') ++st; // 從開頭去除 0 while (cstr[en] == '0') --en; // 從結尾去除 0 if (st > en) { // 整串都是 0 的情況 puts("0"); } else { for (int i = en; i >= st; --i) printf("%c", cstr[i]); // 反向輸出 puts(""); // 換行 } } return 0; }
拿 AC (0ms, 84KB)
。
if (st > en) { // 整串都是 0 的情況 puts("0"); }
不太明白這裡的意思,可以解釋嗎?
if (st > en) { // 整串都是 0 的情況 puts("0"); }
不太明白這裡的意思,可以解釋嗎?
我用舉例說明
以 0
為例,一開始 st = 0, en = 0,經過兩個 while 之後 st 會變 1,en 會變 -1,所以 st > en
以 000000
為例,一開始 st = 0, en = 5,經過兩個 while 之後 st 會變 6,en 還是變 -1,也是 st > en
若中間有不是零的數,如 00100
,再 while 之後 st = en = 2,就不符合該條件 st > en
補充:
再重看自己的 code 發現,在
while (cstr[st] == '0') ++st; while (cstr[en] == '0') --en;
會有 index out of range 的問題,但 zerojudge 還是讓我過了