738. Monotone Increasing Digits

复制代码
/**
 * 738. Monotone Increasing Digits
 * https://leetcode.com/problems/monotone-increasing-digits/description/
 *
 * Given a non-negative integer N, find the largest number that is less than or equal to N with monotone increasing digits.
(Recall that an integer has monotone increasing digits if and only if each pair of adjacent digits x and y satisfy x <= y.)
Example 1:
Input: N = 10
Output: 9
Example 2:
Input: N = 1234
Output: 1234
Example 3:
Input: N = 332
Output: 299
 * */
class Solution {
    fun monotoneIncreasingDigits(N: Int): Int {
        val nArray = N.toString().toCharArray()
        val size = nArray.size
        var j = size//用于记录要转换的位置
        for (i in size - 1 downTo 1) {
            if (nArray[i] >= nArray[i - 1]) {
                continue
            }
            //要找到从后往前遍历的最后一个值升高的位置,让前一位减1
            nArray[i - 1]--
            j = i
        }
        //并把当前位以及后面的所有位都变成9
        for (i in j until size) {
            nArray[i] = '9'
        }
        val sb = StringBuilder()
        for (item in nArray) {
            sb.append(item)
        }
        return sb.toString().toInt()
    }
}
复制代码

 

posted @   johnny_zhao  阅读(79)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)
历史上的今天:
2019-01-31 程序员学习与成长的方法(转发)
点击右上角即可分享
微信分享提示