美文网首页Leetcode
Leetcode 1881. Maximum Value aft

Leetcode 1881. Maximum Value aft

作者: SnailTyan | 来源:发表于2021-09-24 11:39 被阅读0次

    文章作者:Tyan
    博客:noahsnail.com  |  CSDN  |  简书

    1. Description

    Maximum Value after Insertion

    2. Solution

    解析:Version 1,如果n是正数,则x应该位于从左向右找第一个比其小的数字所在的位置,如果是负数,x应该位于从左往右找第一个比其大的数字所在的位置。

    • Version 1
    class Solution:
        def maxValue(self, n: str, x: int) -> str:
            result = ''
            if n[0] == '-':
                i = 0
                while i < len(n) and n[i] <= str(x):
                    i += 1
                result = n[:i] + str(x) + n[i:]
            else:
                i = 0
                while i < len(n) and n[i] >= str(x):
                    i += 1
                result = n[:i] + str(x) + n[i:]
            return result
    

    Reference

    1. https://leetcode.com/problems/maximum-value-after-insertion/

    相关文章

      网友评论

        本文标题:Leetcode 1881. Maximum Value aft

        本文链接:https://www.haomeiwen.com/subject/iyggbltx.html