This is the 8th day of my participation in the August More Text Challenge. For details, see:August is more challenging

The title

Please implement a myAtoi(String s) function that converts a string to a 32-bit signed integer (similar to the AToi function in C/C++).

MyAtoi (string s) ¶

Read the string and discard useless leading Spaces. . Checks whether the next character (assuming it is not at the end of the character) is a positive or negative sign and reads the character (if any). Determine whether the final result is negative or positive. If neither is present, the result is assumed to be positive. . Reads 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 step to integers (i.e., “123” -> 123, “0032” -> 32). If no number is read, the integer is 0. Change the symbol if necessary (starting with Step 2). . If the number of integers exceeds the 32-bit signed integer range [−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 should be fixed to 231 − 1. Returns an integer as the final result.

Note: Whitespace characters in this topic include only space characters' '. Do not ignore any characters except the leading space or the rest of the string after a number.Copy the code
The sample1: Enter: s ="42"Output:42Explanation: The bold string is the character that has been read, and the caret is the character that is currently read. The first1Step:"42"(No character is currently read because there is no leading space) ^ th2Step:"42"No character is currently being read because it does not existThe '-'or'+') ^3Step:"42"(read"42") ^ Parse to an integer42. Due to the"42"In the range [...231.231 - 1], the final result is42Copy the code
The sample2: Enter: s ="- 42"Output: -42Explanation: the first1Step:"- 42"(Read leading space, but ignore) ^ th2Step:"- 42"(readThe '-'Character, so the result should be negative) ^ th3Step:"- 42"(read"42") ^ parse to get an integer -42. Due to the"- 42"In the range [...231.231 - 1], the final result is -42Copy the code
The sample3: Enter: s ="4193 with words"Output:4193Explanation: the first1Step:"4193 with words"(No character is currently read because there is no leading space) ^ th2Step:"4193 with words"No character is currently being read because it does not existThe '-'or'+') ^3Step:"4193 with words"(read"4193"; Since the next character is not a number, the reading stops) ^ parses to an integer4193. Due to the"4193"In the range [...231.231 - 1], the final result is4193Copy the code
The sample4: Enter: s ="words and 987"Output:0Explanation: the first1Step:"words and 987"(No character is currently read because there is no leading space) ^ th2Step:"words and 987"No character is currently being read because it does not existThe '-'or'+') ^3Step:"words and 987"(due to the current character'w'Is not a number, so the reading stops) ^ parses to get an integer0Because no numbers were read. Due to the0In the range [...231.231 - 1], the final result is0Copy the code
The sample5: Enter: s ="91283472332"Output: -2147483648Explanation: the first1Step:"91283472332"(No character is currently read because there is no leading space) ^ th2Step:"91283472332"(readThe '-'Character, so the result should be negative) ^ th3Step:"91283472332"(read"91283472332") ^ parse to get an integer -91283472332. Because -91283472332Less than the range [-231.231 - 1], the final result is truncated to -231 = -2147483648Copy the code

Tip:

0 <= s.long th <= 200s Consists of letters (upper and lower case), numbers (0-9), ‘ ‘, ‘+’, ‘-‘, and ‘.

A little thought

Just saw this question (my heart, good guy topic so often don’t want to write it is certainly difficult), I don’t know if you think so, ha ha ha. If you read the previous examples, this question is simply zhang Fei eat bean sprouts – a piece of cake, so you know the importance of our brush together. If you don’t believe me, let’s go down and see if it’s all done the same way.

Open dry

The general introduction to this function

Both StringBuilder() and toCharArray() are useful here. The function that I’m going to introduce to you today is the Math function and it’s a mathematical function that has a wide range of applications, so let’s see what it does.

Math.E Is a constant that records E. There are some similar constants in Math that are often used in engineering mathematics. Math.abs Take the absolute value math.sin Math.asin arcsine math.cos math.acos Arccosine math.tan Tangent math.atan Arctangent math.atan2 [color=red] [color=red] [color=red] [color=red] [color=red] math. floor [/color] Math.IEEEremainder [/color] Math. Max [/color] Math.min [/color] Math. SQRT [/color] Math. SQRT [/color [color=red] math. pow Raise a number to any power and throw ArithmeticException handle overflow exception [/color] math. exp Raise e to any power math.log1010[color=red] math.round [color=red] math.round [color=red] math.round [color=red] math.round [color=red] math.round [color=red] math.round [color=red] math.roundintType orlongType (returned by the previous functiondoubleType) [/color] math.random returns0.1Between a random numberCopy the code

Source code and analysis

public class test {
	public static String myAtoi(String s) {
		char[] list=s.toCharArray();
		StringBuilder lis=new StringBuilder();
		for(int i=0; i<list.length; i++) {if(list[i]==' ') {
				continue;
			}
			else if(list[i]=='+'||list[i]==The '-'||(Integer.valueOf(list[i])>=48&&Integer.valueOf(list[i])<=57)) {
				lis.append(list[i]);
			}else {
				returnlis.toString(); }}return lis.toString();
	}
	public static void main(String[] args) {
		long a=Integer.parseInt(myAtoi("words and 987") = =""? "0":myAtoi("words and 987"));
		int b= (int) Math.max(Math.min(a, Math.pow(2.31) -1), Math.pow(-2.31)); System.out.println(b); }}Copy the code

Of course this is my own format, not according to the official format. Here we go, one by one:

public static String myAtoi(String s) {
		// The next two lines are the same as before
		char[] list=s.toCharArray();
		StringBuilder lis=new StringBuilder();
		// Convert a string to an integer by the number of times the length of the character
		for(int i=0; i<list.length; i++) {// Start to encounter Spaces according to the problem requirement, discard useless leading Spaces
			if(list[i]==' ') {
			// Continue (); // Continue ()
				continue;
			}// The following judgment is described in detail below
			else if(list[i]=='+'||list[i]==The '-'||(Integer.valueOf(list[i])>=48&&Integer.valueOf(list[i])<=57)) {
				lis.append(list[i]);
			}else {// Return the string if any character other than the above condition is encountered
				returnlis.toString(); }}return lis.toString();
	}
Copy the code
else if(list[i]=='+'||list[i]==The '-'||(Integer.valueOf(list[i])>=48&&Integer.valueOf(list[i])<=57)) {
				lis.append(list[i]);
Copy the code

The Integer. ValueOf () is the function that evaluates the asCLL value for any number between 0 and 9.

  • I think we can just write it this way
else if(list[i]=='+'||list[i]==The '-'||(list[i]>='0'&&list[i]<='9')) {
				lis.append(list[i]);
Copy the code

And then we’re left with the main function part, which is what I’m going to change when I submit it but I’m going to use it when I’m writing the presentation and it’s not in the official format.

public static void main(String[] args) {
// There is a triplet operation involved, but we have already talked about the rule, the main function here is to prevent the following case to return a null character, we will make it zero
		long a=Integer.parseInt(myAtoi("words and 987") = =""? "0":myAtoi("words and 987"));
		// This is the main use of the Math function mentioned above, because the answer is scoped
		// So let's first find the smallest number with the upper bound (2^31) -1
		// Then compare it with minus 2^31 to find the largest number
		int b= (int) Math.max(Math.min(a, Math.pow(2.31) -1), Math.pow(-2.31));
		System.out.println(b);
Copy the code

Ok, that’s all for today’s algorithm problem, did you learn it? In general, this question recalls the previous questions, so I suggest you check it out if you haven’t remembered. Don’t forget what you learned.