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
}
相关推荐
AlenTech15 分钟前
208. 实现 Trie (前缀树) - 力扣(LeetCode)
leetcode
iAkuya16 分钟前
(leetcode)力扣100 36二叉树的中序遍历(迭代递归)
算法·leetcode·职场和发展
wangwangmoon_light24 分钟前
1.1 LeetCode总结(线性表)_枚举技巧
算法·leetcode·哈希算法
有一个好名字1 小时前
力扣-小行星碰撞
算法·leetcode·职场和发展
栈与堆2 小时前
LeetCode-1-两数之和
java·数据结构·后端·python·算法·leetcode·rust
求梦8202 小时前
【力扣hot100题】反转链表(18)
算法·leetcode·职场和发展
求梦8203 小时前
【力扣hot100题】移动零(1)
算法·leetcode·职场和发展
福大大架构师每日一题3 小时前
2026年1月TIOBE编程语言排行榜,Go语言排名第16,Rust语言排名13。C# 当选 2025 年度编程语言。
golang·rust·c#
练习时长一年3 小时前
LeetCode热题100(爬楼梯)
算法·leetcode·职场和发展