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
}
相关推荐
QX_hao2 小时前
【Go】--反射(reflect)的使用
开发语言·后端·golang
夏鹏今天学习了吗3 小时前
【LeetCode热题100(59/100)】分割回文串
算法·leetcode·深度优先
还是码字踏实3 小时前
基础数据结构之数组的双指针技巧之对撞指针(两端向中间):三数之和(LeetCode 15 中等题)
数据结构·算法·leetcode·双指针·对撞指针
hweiyu005 小时前
Go、DevOps运维开发实战(视频教程)
开发语言·golang·运维开发
轮到我狗叫了6 小时前
力扣.84柱状图中最大矩形 力扣.134加油站牛客.abb(hard 动态规划+哈希表)牛客.哈夫曼编码
算法·leetcode·职场和发展
想搞艺术的程序员7 小时前
Go Error 全方位解析:原理、实践、扩展与封装
开发语言·后端·golang
竹等寒7 小时前
Go红队开发—图形化界面
网络安全·golang·个人开发
熬了夜的程序员8 小时前
【LeetCode】99. 恢复二叉搜索树
算法·leetcode·职场和发展
Kent_J_Truman8 小时前
LeetCode Hot100 自用
算法·leetcode·职场和发展