Golang | Leetcode Golang题解之第556题下一个更大元素III

题目:

题解:

Go 复制代码
func nextGreaterElement(n int) int {
    x, cnt := n, 1
    for ; x >= 10 && x/10%10 >= x%10; x /= 10 {
        cnt++
    }
    x /= 10
    if x == 0 {
        return -1
    }

    targetDigit := x % 10
    x2, cnt2 := n, 0
    for ; x2%10 <= targetDigit; x2 /= 10 {
        cnt2++
    }
    x += x2%10 - targetDigit // 把 x2%10 换到 targetDigit 上

    for i := 0; i < cnt; i++ { // 反转 n 末尾的 cnt 个数字拼到 x 后
        d := targetDigit
        if i != cnt2 {
            d = n % 10
        }
        if x > math.MaxInt32/10 || x == math.MaxInt32/10 && d > 7 {
            return -1
        }
        x = x*10 + d
        n /= 10
    }
    return x
}
相关推荐
FfHUCisI25 分钟前
Golang 函数调用的瞬间:栈帧、拷贝栈与逃逸分析
开发语言·后端·golang
王的宝库31 分钟前
Gin 框架实战
golang·gin
aqiu11111110 小时前
【LeetCode 902】最大为 N 的数字组合 - 详细题解与数位组合思路
数据结构·算法·leetcode·蓝桥杯·数位dp
辰烨chenye11 小时前
LeetCode Hot 100 题解 · 哈希篇
算法·leetcode·哈希算法
玖玥拾12 小时前
LeetCode 219 存在重复元素 II
算法·leetcode·哈希算法·散列表
a1879272183114 小时前
【算法】动态规划第四篇:背包收官——min 哨兵、计数世界与组合排列分水岭
算法·leetcode·动态规划·dp·01背包·算法讲解·决策合并
辰烨chenye15 小时前
LeetCode Hot 100 题解 · 子串篇
算法·leetcode·职场和发展
辰烨chenye15 小时前
LeetCode Hot 100 题解 · 堆篇
java·算法·leetcode
techdashen18 小时前
Go Map 详解:键值对实际上是如何存储的
开发语言·后端·golang