編寫 long fun(long int x),將 x 中每一位上的奇數字符提取,逆序組成新數返回。例:123456789 → 97531。
x % 10 取末位)digit % 2 == 1)result = result * 10 + digit(自動實現逆序)x /= 10 繼續下一位
#include
long fun(long int x) {
long result = 0;
while (x != 0) {
int digit = x % 10;
if (digit % 2 == 1) { // 奇數位
result = result * 10 + digit; // 逆序拼接
}
x /= 10;
}
return result;
}
int main() {
long a, b;
printf("Please input a long int num: ");
scanf("%ld", &a);
b = fun(a);
printf("b=%ld\n", b);
return 0;
}
| 輸入 | 輸出 | 說明 |
|---|---|---|
| 123456789 | 97531 | 正常情況 |
| 24680 | 0 | 無奇數位 |
| 13579 | 97531 | 全奇數位 |
| -12345 | 531 | 負數處理(C 語言 % 可能為負,建議取絕對值) |
long long 或字符串x = x < 0 ? -x : x;