题目:
题解:
class Solution:def nextGreaterElement(self, n: int) -> int:x, cnt = n, 1while x >= 10 and x // 10 % 10 >= x % 10:cnt += 1x //= 10x //= 10if x == 0:return -1targetDigit = x % 10x2, cnt2 = n, 0while x2 % 10 <= targetDigit:cnt2 += 1x2 //= 10x += x2 % 10 - targetDigit # 把 x2 % 10 换到 targetDigit 上MAX_INT = 2 ** 31 - 1for i in range(cnt): # 反转 n 末尾的 cnt 个数字拼到 x 后d = n % 10 if i != cnt2 else targetDigit# 为了演示算法,请读者把 x 视作一个 32 位有符号整数if x > MAX_INT // 10 or x == MAX_INT // 10 and d > 7:return -1x = x * 10 + dn //= 10return x