在线编译器 C

#include <stdio.h> #include <string.h> int main() { char str[20]; // 1. 读取输入的数字字符串 (不超过 10^10 对应最多 11 位数) if (scanf("%s", str) != 1) { return 0; } int len = strlen(str); int swapped = 0; // 2. 从左到右寻找最佳的交换位置 for (int i = 0; i < len - 1; i++) { int max_idx = i; // 在当前位置 i 的右侧寻找最大的数字 for (int j = i + 1; j < len; j++) { // 注意:当数字相同时,选择最右边(靠后)的那个,所以用 >= if (str[j] >= str[max_idx]) { max_idx = j; } } // 如果右侧的最大数字严格大于当前位置的数字,则进行交换 if (str[max_idx] > str[i]) { char temp = str[i]; str[i] = str[max_idx]; str[max_idx] = temp; swapped = 1; break; // 只能交换一次,完成即可退出 } } // 3. 输出最终结果并换行 printf("%s\n", str); return 0; }
This code reads a number as a string, then tries to make the number larger by swapping exactly one pair of digits. It scans from left to right, finds the largest digit to the right of the current position, and if that digit is larger, it swaps them and stops.

- The condition `str[j] >= str[max_idx]` uses `>=` to prefer the rightmost occurrence of the largest digit. However, when digits are equal, swapping with a later equal digit does not change the number, but it might prevent a better swap later. Consider whether you want to swap with the rightmost largest digit or the leftmost largest digit that is strictly greater than the current digit.

- The loop breaks after the first swap, but the problem might require you to consider all possible single swaps and choose the one that gives the largest resulting number. Your current approach picks the first position where a larger digit exists to the right, but that may not always produce the maximum possible number after one swap.