Found nuggets of a small egg: personal home page, mouse placed on the avatar, avatar will turn, the faster, naughty programmer O(∩_∩).

  1. String to integer

MyAtoi (string s) converts a string to a 32-bit signed integer (similar to atoi in C/C++).

MyAtoi (string s)

  • Read in the string and discard useless leading whitespace
  • Checks whether the next character (assuming it has not reached the end of the character) is a plus or minus sign and reads that character (if any). Determine whether the final result is negative or positive. If neither exists, the result is assumed to be positive.
  • Read the next character until the next non-numeric character is reached or the end of the input is reached. The rest of the string is ignored.
  • Convert the numbers read in the previous steps to integers (that is, “123” -> 123, “0032” -> 32). If no number is read in, the integer is 0. Change symbols as necessary (starting with Step 2).
  • If the number of integers exceeds the range of 32-bit signed integers [−231, 231 − 1], truncate the integer to keep it within the range. Specifically, integers less than −231 should be fixed to −231 and integers greater than 231 − 1 to 231 − 1.
  • Returns an integer as the final result.

Note: Whitespace characters in this case only include the space character ‘ ‘. Do not omit any characters other than those following a leading space or number.

Source: LeetCode link: leetcode-cn.com/problems/st… Copyright belongs to the Collar buckle network. Commercial reprint please contact official authorization, non-commercial reprint please indicate the source.

Well, it’s kind of crazy to give an algorithm for a problem and, of course, since it’s a document, I’m going to exclude the use of the Go Atoi function, the Strconv package.

B. Go C. Go D. Go

  1. How to convert a character to the corresponding number in Go, i.e. how to convert ‘2’ to the number 2:
package main
import (
    "bytes"
    "encoding/binary"
    "fmt"
)
func main(a)  {
	s := "0123"
	s_w1 := int(s[0]) // Display the conversion directly
	fmt.Println(s_w1) // 48, which is the decimal digit '0' in ASCII
	// We can convert characters '0'-'9' to corresponding int numbers in the following way
	s_w2 := int(s[0] - '0') 
	fmt.Println(s_w2)
    // Find the method of the document: wrong method
	// fmt.Println(ByteToInt(s[0]))
}

/** * this is my understanding wrong, this is wrong, wrong!! * /
// func ByteToInt(bys byte) int {
// temp := make([]byte, 1)
// temp[0] = bys
// bytebuff := bytes.NewBuffer(temp)
// var data int64
// binary.Read(bytebuff, binary.BigEndian, &data)
// return int(data)
// }
Copy the code

Why? Because I initially misunderstood that a byte could be converted to an int by a binary operation, which is not the case. In the program I borrowed, the parameter ByteToInt is not a single byte, but []byte, that is, multiple bytes would have to be converted to an int, and ‘2’, the ASCII code 0011 0010 converted to the integer 2, is really, in essence, the difference between ‘2’ and ‘0’.

The code is concerned with the big-endian mode: big-endian mode, where the high bytes of data are stored in the low address of memory, and the low bytes of data are stored in the high address of memory. In the small-endian mode, the high bytes of data are stored in the high address of memory, and the low bytes of data are stored in the low address of memory. For starters, let’s not get bogged down in these details. Just remember that “Golang is usually big-endian.”

For example, for data :0x12345678, from high byte to low byte: 12345678, from low byte to high byte :78563412. According to the big-end mode, from low BUF [0] to high BUF [3], it should be 12, 34, 56, 78. It should be 78,56,34,12 from low buf[0] to high buf[3] according to the small-end mode.

Personal understanding of small – and large-end patterns in the GO language

  1. How to represent numeric boundaries in Go: In integer inversion we looked in detail at integer types in Go and how to represent numeric boundaries for 32-bit integers.
const MAX_UINT32 = ^uint32(0)
const MIN_UINT32 = 0
// Maximum unsigned drop sign bit
const MAX_INT32 = int(MAX_UINT32 >> 1)
const MIN_INT32 = - MAX_INT32 - 1
Copy the code
  1. How to use regular expressions in Go: See the Google RE2 syntax documentation for regular expressions and Wikipedia regular expressions for more information. Go commonly used regular method can refer to the nuggets article: Go regular expression use, sample code is as follows
package main
import (
    "fmt"
    "regexp"
)
func main(a) {
    buf := "weialfidnd8930232jdjfkdjka09232"
    // Parses the regular expression and returns to the interpreter on success
    reg1 := regexp.MustCompile(`\d.\d`)
    if reg1 == nil {
        fmt.Println("regexp err")
        return
    }

    The second parameter indicates that only the first n matches are searched, and if n<0, all matches are searched
    result1 := reg1.FindAllStringSubmatch(buf, - 1)
	// result1 := reg1.FindAllString(buf, -1)
	fmt.Println("result1 = ", result1)
	for _, v := range result1 {
		fmt.Println("find = ", v[0])}// The second argument returns error, nil if there is no error
	match, _ := regexp.MatchString("p([a-z]+)ch"."peach")
    fmt.Println(match)
}
Copy the code

In my opinion, proficiency in regular expressions, network API, collection and list processing is a prerequisite for “mastering a language”. Java should also include proficiency in stream library.

View the limited state automata on the official website of force button to solve, it is easy to understand, not elaborate. We give the Go language regular expression solution, reference to a Python solution of the ligo:

import (
	"regexp"
	"strings"
)

const MAX_UINT32 = ^uint32(0)	
	const MIN_UINT32 = 0
	// Maximum unsigned drop sign bit
	const MAX_INT32 = int(MAX_UINT32 >> 1)
	const MIN_INT32 = - MAX_INT32 - 1


func stringToInt(s string) int  {

	i, num := 0.0
	if s[0] = =The '-' || s[0] = ='+' {
		i = 1
	}

	for ; i < len(s); i++ {
		popNum := int(s[i] - '0')
		if (num > MAX_INT32/10) || (num == MAX_INT32/10 && popNum > 7) || (num < MIN_INT32/10) || (num == MIN_INT32/10 && popNum < - 8 -) {
			if s[0] = =The '-' {
				return MIN_INT32
			} else {
				return MAX_INT32
			}
		}
		num = num*10 + popNum
	}

	if s[0] = =The '-' {
		return -num
	} else {
		return num
	}
}


func myAtoi(s string) int {

	// remove whitespace
	str := strings.TrimSpace(s)
	// # interpreter: ^ indicates the start of a substring, \d indicates a number. Indicates that the substring begins with '+', '-', or a number and is followed by at least one number
	reg1 := regexp.MustCompile(` ^ [\ + \]? \d+`)
	// Find the first matching substring

	numArray := reg1.FindAllStringSubmatch(str, 1)
	if len(numArray) == 0 {
		return 0
	}
	num := stringToInt(numArray[0] [0])
	// num = int(*num) # unpack and convert to integer
	return max(min(num,MAX_INT32), MIN_INT32)    / / # return values
	// return num
}

func min(num1, num2 int) int  {
	if num1 < num2 {
		return num1
	}
	return num2
}

func max(num1, num2 int) int  {
	if num1 < num2 {
		return num2
	}
	return num1
}
Copy the code

The code is more complex than it looks o(╥﹏╥)o


Go language power buckle brush series of articles | Go theme month

  1. Go language power buckle brush – the sum of two numbers | Go theme month
  2. Go language power buckle brush – add two numbers | Go theme months
  3. Go language power button brush title – the largest string without repeating characters | Go theme month
  4. Go language power button brush questions – find the median of two positive ordinal groups | Go theme months
  5. Go language power button brush – the longest echo sub string | Go theme month
  6. Go language power buckle brush -Z font transformation | Go theme month
  7. Go language force button brush title – integer reversal | Go theme month