TLP-Task02 study notes


This article is the 21st LeetCode selected topic group Task01 study notes of the Datawhale team study plan.
For beginners, time is a bit rushed, many solutions are not analyzed in detail, and will be revised in the future, forgive me.
All topics refer to the Datawhale learning document, open source address:
https://github.com/datawhalechina/team-learning-program/tree/master/LeetCodeTencent

007 integer inversion

Source: LeetCode
Link: https://leetcode-cn.com/problems/reverse-integer

Given a 32-bit signed integer, you need to invert the digits on each of the integers.

Note:
Assuming that our environment can only store 32-bit signed integers, the value range is [−2^31, 2^31 − 1]. According to this assumption, if the integer overflows after the inversion, it returns 0.

Example

Input: x = 123, output: 321
input: x = -123, output: -321
input: x = 120, output: 21
input: x = 0, output: 0

Ideas

This question mainly considers the problem of overflow. Main idea reference:
https://leetcode-cn.com/problems/reverse-integer/solution/zheng-shu-fan-zhuan-by-leetcode/ (Official problem solution, method: pop and push numbers & check before overflow )
Https://leetcode-cn.com/problems/reverse-integer/solution/tu-jie-7-zheng-shu-fan-zhuan-by-wang_ni_ma/ The
second method is easier to understand, which is to constantly take the modulus. Get the last number, and judge whether it overflows every time.

Python implementation

Code source

class Solution:
    def reverse(self, x: int) -> int:
        res = 0
        x1 = abs(x)
        while(x1!=0):
            temp = x1%10 # 取末尾数字
            if res > 214748364 or (res==214748364 and temp>7):
                return 0 # 判断溢出
            if res<-214748364 or (res==-214748364 and temp<-8):
                return 0
            res = res*10 +temp
            x1 //=10 # 地板除,得到整数
        return res if x >0 else -res
        

008 String conversion integer (atoi)

Source: LeetCode
Link: https://leetcode-cn.com/problems/string-to-integer-atoi

Please implement an atoi function to convert a string to an integer.
First, the function discards useless beginning space characters as needed, until it finds the first non-space character. The following conversion rules are as follows:

  • If the first non-blank character is a positive or negative sign, combine this sign with as many consecutive numeric characters as possible after it to form a signed integer.
  • If the first non-blank character is a number, it is directly combined with the following consecutive number characters to form an integer.
  • The string may also have extra characters after the valid integer part, so these characters can be ignored and they should not affect the function.
  • If the first non-space character in the string is not a valid integer character, the string is empty, or the string contains only blank characters, your function does not need to be converted, that is, it cannot be converted effectively.
  • In any case, if the function cannot perform a valid conversion, please return 0.

note:

The blank characters in this question only include the space character ''.
Assuming that our environment can only store 32-bit signed integers, the value range is [−2^31, 2^31 − 1]. If the value exceeds this range, please return 2^31 − 1 or −2^31.

Example

Input: "42" Output: 42

Input: "-42" Output: -42 (note that there is a space _ before -42)
Explanation: The first non-blank character is'-', which is a negative sign.
We try our best to combine the minus sign with all subsequent numbers, and finally get -42.

Input: "4193 with words"
Output: 4193
Explanation: The conversion ends at the number '3' because the next character is not a number.

Input: "words and 987"
Output: 0
Explanation: The first non-empty character is'w', but it is not a number or positive or negative sign.
Therefore, effective conversion cannot be performed.

Input: "-91283472332"
Output: -2147483648
Explanation: The number "-91283472332" exceeds the range of a 32-bit signed integer.
Therefore INT_MIN (−231) is returned.

prompt:

0 <= s.length <= 200
s is composed of English letters (uppercase and lowercase), numbers, '','+','-' and'.'

Ideas

Reference question solution: https://leetcode-cn.com/problems/string-to-integer-atoi/solution/python-1xing-zheng-ze-biao-da-shi-by-knifezhu/
mainly uses regular expressions in python :

^: the beginning of the matching string
[+-]: represents a + character or-character
?: the preceding character is optional
\d: a number
+: one or more of the preceding character
\D: a non-digit character
* : 0 or more
max(min(number, 2**31-1), -2**31) of the previous character to prevent out of bounds

(By the way, add the ** bold part ** when you just learned markdown typesetting , you can add \escaping to display the * sign normally)

achieve

(Regular expression yyds!)

class Solution:
    def myAtoi(self, s: str) -> int:
        return max(min(int(*re.findall('^[\+\-]?\d+', s.lstrip())), 2**31 - 1), -2**31)

Step by step

import re
class Solution:
    def myAtoi(self, str: str) -> int:
        INT_MAX = 2147483647    
        INT_MIN = -2147483648
        str = str.lstrip()      #清除左边多余的空格
        num_re = re.compile(r'^[\+\-]?\d+')   #设置正则规则
        num = num_re.findall(str)   #查找匹配的内容
        num = int(*num) #由于返回的是个列表,解包并且转换成整数
        return max(min(num,INT_MAX),INT_MIN)    #返回值
       

009 palindrome

Source: LeetCode
Link: https://leetcode-cn.com/problems/palindrome-number

Determine whether an integer is a palindrome. The palindrome number refers to the same integer in both positive order (from left to right) and reverse order (from right to left).
Can you solve this problem without converting integers to strings?

Example

Input: 121
Output: true

Input: -121
Output: false
Explanation: Reading from left to right, it is -121. Reading from right to left, it is 121-. Therefore it is not a palindrome.

Input: 10
Output: false
Explanation: Reading from right to left, it is 01. Therefore it is not a palindrome.

Ideas

  • Rule out some situations first:

All negative numbers cannot be palindromes,
except for 0, all numbers whose ones place is 0 cannot be palindromes, because the highest bit is not equal to 0.
Official solution

  • The title does not require a character string. You can consider repeatedly taking the modulo to obtain the reversed number, and then compare it with the original number.
    For example, the number of palindrome is 13531, rN:1→13→135, x: 1353→135.

  • Analyzing conditions:while x > revertedNumber

Since the whole process we keep dividing the original number by 10, and then multiplying the inverted number by 10, when the original number is less than or equal to the inverted number, it means that we have processed half of the digits. Up.

Regardless of whether it is a palindrome or not, the number of reversal digits is greater than or equal to n/2 to leave the loop.
The number of palindrome is 13531, it is judged that 135=135, return 1; the
number of non-palindrome is 654321, it is judged that 123<654, the next time 1234>65, return 0.

python implementation

Source: https://leetcode-cn.com/problems/palindrome-number/solution/hui-wen-shu-by-leetcode-solution/436848 The
comment is added by the author.

class Solution:
    def isPalindrome(self, x: int) -> bool:
    	# 直接排除特殊情况
        if x < 0 or (x % 10 == 0 and x != 0):
            return False
          
        revertedNumber = 0 # 反转后的数字
        while x > revertedNumber:
            revertedNumber = revertedNumber * 10 + x % 10
            x //= 10 # 取整,取原数前n-1位
        return x == revertedNumber or x == revertedNumber // 10
		# 当数字长度为奇数时,通过 revertedNumber/10 去除处于中位的数字
		

Guess you like

Origin blog.csdn.net/cosima0/article/details/112545050