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
}
相关推荐
YoloMari12 分钟前
Leetcode刷题-枚举右,维护左
python·算法·leetcode
Pyroyster5 小时前
【LeetCode222】完全二叉树的节点个数
算法·leetcode·职场和发展
S01d13r5 小时前
LeetCode 解题思路 16(Hot 100)
算法·leetcode·职场和发展
fantasy_45 小时前
LeetCode455☞分发饼干
python·算法·leetcode·贪心算法
熊峰峰5 小时前
2.3 滑动窗口专题:最大连续1的个数 III(LeetCode 1004)
数据结构·c++·算法·leetcode
Dream it possible!8 小时前
LeetCode 热题 100_前 K 个高频元素(73_347_中等_C++)(堆)(哈希表+排序;哈希表+优先队列(小根堆))
数据结构·c++·leetcode·散列表
虽千万人 吾往矣11 小时前
golang算法二叉树对称平衡右视图
开发语言·算法·golang
酷酷的崽79816 小时前
【栈数据结构应用解析:常见算法题详细解答】—— Leetcode
数据结构·算法·leetcode
誓约酱19 小时前
(每日一题) 力扣 179 最大数
c语言·c++·算法·leetcode·职场和发展
2301_7921858819 小时前
力扣:3305.元音辅音字符串计数
c++·算法·leetcode