leetcode--670. Maximum Swap

Source: Internet
Author: User
Topics

Given a non-negative integer, you could swap both digits at most once to get the maximum valued number. Return the maximum valued number you could get.

Example 1:
input:2736
output:7236
Explanation:swap the number 2 and the number 7.
Example 2:
input:9973
output:9973
Explanation:no swap.
Note:
The given number is in the range [0, 108]
Swap only two digits in an integer to get the maximum value idea

Scan from high to low, if the number of subsequent bits is greater than the value of the current bit, the maximum value is obtained after the swap position. Code

class Solution {public:///integer array to int int toint (int* arr, int n) {int res = 0;
        for (int i=0; i<n; i++) {res = res*10 + arr[i];
    } return res;
        } int maximumswap (int num) {/////First get array of each digit int arr[20] = {0};
        int back = num, n = 0;
            while (back) {arr[n++] = back% 10;
        Back/= 10;
        } for (int i=0, j=n-1; i<j; i++, j--) swap (Arr[i], arr[j]);
            Scan from high to low for (int i=0; i<n; i++) {int maxn = arr[i];
            int index = i;
                    for (int j=i+1; j<n; J + +) {if (Arr[j] >= maxn) {index = j;
                MAXN = Arr[j];
                }} if (Maxn > Arr[i]) {swap (Arr[i], arr[index]);
            Return ToInt (arr, n);
    }} return num;
}
}; 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.