当前位置:网站首页>Algorithm -- maximum number after parity exchange (kotlin)

Algorithm -- maximum number after parity exchange (kotlin)

2022-06-21 17:36:00 Xiaomi technology Android R & D caoxinyu

subject

Give you a positive integer num . You can exchange num in Parity Any two digits of the same ( namely , Are odd or even ).

Return to exchange arbitrarily After that num Of Maximum It may be worth .

Example 1:

Input :num = 1234
Output :3412
explain : Exchange numbers 3 And number 1 , The result is 3214 .
Exchange numbers 2 And number 4 , The result is 3412 .
Be careful , There may be other exchange sequences , But it can be proved that 3412 Is the maximum possible value .
Be careful , You can't exchange numbers 4 And number 1 , Because they have different parity .
Example 2:

Input :num = 65875
Output :87655
explain : Exchange numbers 8 And number 6 , The result is 85675 .
Exchange numbers 5 And number 7 , The result is 87655 .
Be careful , There may be other exchange sequences , But it can be proved that 87655 Is the maximum possible value .

Tips :

1 <= num <= 109

source : Power button (LeetCode)
link :https://leetcode.cn/problems/largest-number-after-digit-swaps-by-parity
Copyright belongs to the network . For commercial reprint, please contact the official authority , Non-commercial reprint please indicate the source .

Solutions

 Convert numbers to strings numStr;
 establish 2 A priority queue , Separate storage num Odd and even numbers in , And they are arranged in reverse order ;
 Replace the original odd or even numbers in the arranged order .

resolvent

    fun largestInteger(num: Int): Int {
    
        if (num == 0) {
    
            return 0
        }
        var q1 = PriorityQueue(Collections.reverseOrder<Int>())
        var q2 = PriorityQueue(Collections.reverseOrder<Int>())
        val charArray = num.toString().toCharArray()
        charArray.forEach {
    
            val value = it - '0'
            when(value % 2){
    
                0 ->{
     q1.offer(value)}
                else ->{
    q2.offer(value)}
            }
        }
        var result = 0
        charArray.forEach {
    
            val value = it - '0'
            result = when(value % 2){
    
                0 ->{
    
                    result* 10 + q1.poll()
                }
                else ->{
    
                    result* 10 + q2.poll()
                }
            }
        }
        return result
    }

summary

1. Pay attention to the examination It is exchanged according to the parity of a single number , Not location
2. When splicing numbers ,result = result* 10 + q1.poll() instead of result += result* 10 + q1.poll()

原网站

版权声明
本文为[Xiaomi technology Android R & D caoxinyu]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/172/202206211522584653.html