1

I am trying to find the maximum of a number by swapping two digits. I have written the correct logic and it is getting to the part where I need to swap however after the swap i return the result and it isn't swapping?

var maximumSwap = function(num) {
   let str = num.toString()
   let left = 0
   let right = 1

   while (left !== str.length) {
     if (parseInt(str[left]) < parseInt(str[right])) {
       console.log(str[left], str[right])
       let temp = str[left];
       str[left] = str[right];
       str[right] = temp;
       return str
     } else if (parseInt(str[left]) > parseInt(str[right])) {
       if (left === right) {
         left++
         right = left + 1
       } else if (left < right) {
         right++
       }
     }

   }
};

maximumSwap(2736)
// Input: 2736
// Output: 7236
// Explanation: Swap the number 2 and the number 7.


2 Answers 2

1

String are immutable in JS. Even though you are changing characters at left and right position, it wont reflect in "str".

Use this link on how to replace characters: How do I replace a character at a particular index in JavaScript?

Also, your logic is incorrect, if the first position element is largest, loop will run infinite times.

Sign up to request clarification or add additional context in comments.

Comments

0
// u can convert the num to string array to exchange
const str = num.toString().split('')

there is an example

// Input: 2736
// Output: 7632
var maximumSwap = function(num) {
   let str = num.toString().split('')
   let left = 0
   let right = 1

   while (left < str.length - 1) {
     while(right < str.length) {
        if (parseInt(str[left]) < parseInt(str[right])) {
          // exchange
          [str[left], str[right]] = [str[right], str[left]]
        }
        right++
     }
     left++
     right = left
   }
   return str.join('')
};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.