3-5 lines, Python/C++/Java/Ruby


  • 3

    Python:

    def maximumSwap(self, num):
        places = [10**i for i in range(len(str(num)))]
        return max(num + num/p%10*(q-p) + num/q%10*(p-q)
                   for p in places for q in places)
    

    C++:

    int maximumSwap(int num) {
        int maxi = 0;
        for (int p=1; p<=num; p*=10)
            for (int q=p; q<=num; q*=10)
                maxi = max(maxi, num + num/p%10*(q-p) + num/q%10*(p-q));
        return maxi;
    }
    

    Java:

    public int maximumSwap(int num) {
        int max = 0;
        for (int p=1; p<=num; p*=10)
            for (int q=p; q<=num; q*=10)
                max = Math.max(max, num + num/p%10*(q-p) + num/q%10*(p-q));
        return max;
    }
    

    Ruby:

    def maximum_swap(num)
      num.to_s.size
        .times.map { |i| 10**i }.repeated_combination(2)
        .map { |p, q| num + num/p%10*(q-p) + num/q%10*(p-q) }
        .max
    end
    

    There are so very few possibilities that I just try them all, swapping between any two places p and q (where places are 1, 10, 100, 1000, etc, i.e., the "ones place", "tens place", "hundreds place", etc). With num/p%10 I get the digit at place p, and multiplying it with (q-p) takes it out of place p and puts it into place q. And move the digit from place q to place p the same way.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.