LeetCode's 25th bi-weekly contest 5385. The maximum difference that can be obtained by changing an integer

Topic link

Insert picture description hereInsert picture description here

  • At the time, I thought that the 10^8 data would time out if I directly simulate it, so I didn’t think about it but used violence. It seems that I still think too much. If I simulate directly, the idea is very clear, as long as two nesting of 0 to 10. Cycle through each number to find the maximum and minimum values.
    code show as below:
class Solution {
    
    
public:
    int maxDiff(int num) {
    
    
        string s = to_string(num);
        int maxi = INT_MIN, mini = INT_MAX;
        for (int i = 0; i < 10; ++i){
    
    
            for (int j = 0; j < 10; ++j){
    
    
                string t = s;
                if (j==0&&t[0]==i) continue;
                for (char& c: t)
                    if (c == i + '0')   
                        c = j + '0';
                
                int dd = stoi(t);
                if (dd == 0) continue;
                maxi = max(maxi, dd);
                mini = min(mini, dd);
            }
            
        }
        return maxi - mini;
    }
};

Guess you like

Origin blog.csdn.net/qq_43663263/article/details/105902786