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
}
相关推荐
鱼跃鹰飞23 分钟前
Leetcode会员尊享100题:270.最接近的二叉树值
数据结构·算法·leetcode
We་ct2 小时前
LeetCode 205. 同构字符串:解题思路+代码优化全解析
前端·算法·leetcode·typescript
chillxiaohan3 小时前
GO学习记录——多文件调用
开发语言·学习·golang
蒟蒻的贤5 小时前
leetcode链表
算法·leetcode·链表
执着2595 小时前
力扣hot100 - 94、二叉树的中序遍历
数据结构·算法·leetcode
Grassto7 小时前
11 Go Module 缓存机制详解
开发语言·缓存·golang·go·go module
福大大架构师每日一题8 小时前
ollama v0.15.2发布:新增Clawdbot集成指令,全面支持Ollama模型启动!
golang·ollama
老鼠只爱大米10 小时前
LeetCode经典算法面试题 #114:二叉树展开为链表(递归、迭代、Morris等多种实现方案详细解析)
算法·leetcode·二叉树·原地算法·morris遍历·二叉树展开
参.商.10 小时前
【Day25】26.删除有序数组中的重复项 80.删除有序数组中的重复项II
leetcode·golang
小高Baby@10 小时前
ShouldBind、ShouldBindJson、ShouldBindQuery的区别
后端·golang