当前位置:网站首页>算法--按奇偶性交换后的最大数字(Kotlin)
算法--按奇偶性交换后的最大数字(Kotlin)
2022-06-21 16:05:00 【小米科技Android 研发曹新雨】
题目
给你一个正整数 num 。你可以交换 num 中 奇偶性 相同的任意两位数字(即,都是奇数或者偶数)。
返回交换 任意 次之后 num 的 最大 可能值。
示例 1:
输入:num = 1234
输出:3412
解释:交换数字 3 和数字 1 ,结果得到 3214 。
交换数字 2 和数字 4 ,结果得到 3412 。
注意,可能存在其他交换序列,但是可以证明 3412 是最大可能值。
注意,不能交换数字 4 和数字 1 ,因为它们奇偶性不同。
示例 2:
输入:num = 65875
输出:87655
解释:交换数字 8 和数字 6 ,结果得到 85675 。
交换数字 5 和数字 7 ,结果得到 87655 。
注意,可能存在其他交换序列,但是可以证明 87655 是最大可能值。
提示:
1 <= num <= 109
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/largest-number-after-digit-swaps-by-parity
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解决思路
将数字转换为字符串numStr;
创建2个优先队列,分别存放num中的奇数和偶数,并都以倒序排列;
按照排好的顺序依次替换原来的奇数或偶数。
解决方法
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
}
总结
1.注意审题 是按照单个数字的奇偶进行兑换,而不是位置
2.数字拼接的时候,result = result* 10 + q1.poll() 而不是result += result* 10 + q1.poll()
边栏推荐
- 【mysql学习笔记18】约束
- win32com 操作excel
- What does container cloud mean? What is the difference with fortress machine?
- Why did you win the first Taosi culture award of 20000 RMB if you are neither a top R & D expert nor a sales bull?
- uni-app框架学习笔记
- iframe跨域传值
- Still using xshell? Try this cool SSH terminal tool, which is very powerful!
- 牛客网:大数加法
- 软件测试体系学习及构建(13)-测试基础之测试工程师的基本要求
- Google play 应用签名密钥证书,上传签名证书区别
猜你喜欢

窗帘做EN 1101易燃性测试过程是怎么样的?

关于SSM整合,看这一篇就够了~(保姆级手把手教程)

QT5知识:字符串列表QStringListModel

Nanjing University static program analyses -- Introduction learning notes

【毕业N年系列】 毕业第四年

How can aggressive programmers improve R & D efficiency Live broadcast Preview

Many software companies are actually "jokes"

Serialization and deserialization of binary tree

Redis6.0新特性(上)

软件测试体系学习及构建(14)-测试基础之软件测试和开发模型概述
随机推荐
[MySQL learning notes 17] sorting out common functions
Set up your own website (11)
The beta version of move protocol is stable, and it is temporarily decided to expand the scale of the prize pool
Not this year's 618?
Calculation of carbon emissions
大话内存四区
[MySQL learning notes 18] constraints
疫情数据对应的大陆和全球的矢量数据下载,基于geojson转shp
Serialization and deserialization of binary tree
QT knowledge: using the qgraphicspixmapitem class
【mysql学习笔记11】排序查询
fs. Readfile() and fs writeFile()
The next stop of Intelligent Manufacturing: cloud native + edge computing two wheel drive
【mysql学习笔记13】查询语句综合练习
Why did you win the first Taosi culture award of 20000 RMB if you are neither a top R & D expert nor a sales bull?
【mysql学习笔记19】多表查询
Four areas of telephone memory
全国行政区划
Sorting out Android kotlin generic knowledge points
Variables and pointers