leetcode 1323. Maximum 69 Number 详解 python3

一.问题描述

Given a positive integer num consisting only of digits 6 and 9.

Return the maximum number you can get by changing at most one digit (6 becomes 9, and 9 becomes 6).

 

Example 1:

Input: num = 9669
Output: 9969
Explanation: 
Changing the first digit results in 6669.
Changing the second digit results in 9969.
Changing the third digit results in 9699.
Changing the fourth digit results in 9666. 
The maximum number is 9969.

Example 2:

Input: num = 9996
Output: 9999
Explanation: Changing the last digit 6 to 9 results in the maximum number.

Example 3:

Input: num = 9999
Output: 9999
Explanation: It is better not to apply any change.

 

Constraints:

  • 1 <= num <= 10^4
  • num's digits are 6 or 9.

二.解题思路

emmm,大水题,主要是想把近段时间出的easy题给补上,当是熟悉熟悉字符串的操作吧,几个函数。

比如说 replace函数,index函数,join函数。

这道题当然也可以自己连除获得num的每一位,不过这种实现在之前的几道题都写了,然后在这道题中并没有啥优化的,还是要转化成字符串处理。

1.可以直接转化成字符串然后用replace函数。

2.可以自己把字符串每一位存在列表里面然后找到6换成9.

PS:字符串对象是不能直接给元素赋值的,因此要先转换成列表。

更多leetcode算法题解法: 专栏 leetcode算法从零到结束  或者 leetcode 解题目录 Python3 一步一步持续更新~

三.源码

#version 1, 1 line
class Solution:
    def maximum69Number (self, num: int) -> int:
        return str(num).replace('6','9',1)

#version 2, from others work in leetcode
class Solution:
    def maximum69Number (self, num: int) -> int:
        str_num = str(num)
        if '6' in str_num:
            pos = str_num.index('6')
            list_num = list(str_num)
            list_num[pos] = '9'
            str_num = ''.join(list_num)
            return int(str_num)
        else:
            return num

#version 3, from others work in leetcode
class Solution:
    def maximum69Number (self, num: int) -> int:
        s = str(num)
        lst = []
        for i in s:
            lst.append(i)
        for i in range(len(lst)):
            if lst[i] == '6':
                lst[i] = '9'
                break
        s = ''.join(lst)
        return int(s)

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值