Created
August 16, 2025 17:52
-
-
Save tatsuyax25/66d0695893e7f2d53c8f5cc372027a32 to your computer and use it in GitHub Desktop.
You are given a positive integer num consisting only of digits 6 and 9. Return the maximum number you can get by changing at most one digit (6 becomes 9, and 9 becomes 6).
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @param {number} num | |
* @return {number} | |
*/ | |
var maximum69Number = function(num) { | |
// Convert the number into an array of digits | |
const digits = num.toString().split(''); | |
let maxNum = num; | |
// Try flipping each digit one by one | |
for (let i = 0; i < digits.length; i++) { | |
// Clone the original digits array | |
const tempDigits = [...digits]; | |
// Flip the current digit if it's 6 or 9 | |
if (tempDigits[i] === '6') { | |
tempDigits[i] = '9'; | |
} else if (tempDigits[i] === '9') { | |
tempDigits[i] = '6'; | |
} | |
// Convert back to number and compare | |
const newNum = parseInt(tempDigits.join(''), 10); | |
maxNum = Math.max(maxNum, newNum); | |
} | |
return maxNum; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment