top1编程
← 返回题目
题解

【入门】求三位数打乱次序后最大数和最小数的差值是多少

1 条题解

  • 0
    @ 2026-7-29 0:16:29
    #include <iostream>
    #include <string>
    #include <algorithm>
    using namespace std;
    
    int main() {
        int n;
        cin >> n;
    
        // 转为字符串,便于取每一位
        string s = to_string(n);
    
        // 排序:升序 → 最小数;降序 → 最大数
        sort(s.begin(), s.end());
        string min_str = s;  // 升序
        string max_str = s;  // 先复制,再反转
        reverse(max_str.begin(), max_str.end());
    
        // 转换为整数(自动忽略前导零)
        int min_num = stoi(min_str);
        int max_num = stoi(max_str);
    
        int diff = max_num - min_num;
    
        cout << diff << endl;
    
        return 0;
    }
    
    • 1