SoFunction
Updated on 2025-03-02

Practice Java functions and algorithms every day Math functions summary and string conversion integers

topic

Please implement a myAtoi(string s) function to convert a string into a 32-bit signed integer (similar to atoi in C/C++
function).

The algorithm of the function myAtoi(string s) is as follows:

Read in the string and discard useless leading spaces.
Check whether the next character (assuming that it has not yet reached the end of the character) is positive or negative, and read that character (if any). Determine whether the final result is a negative or positive number. 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 will be ignored.
Convert these numbers read in the previous step into integers (i.e., "123" -> 123, "0032" -> 32). If no number is read, the integer is 0. Change the symbol if necessary (start from step 2).
If the integer number exceeds the 32-bit signed integer range [−231, 231 − 1], this integer needs to be truncated to keep it within this range. Specifically, integers smaller than −231 should be fixed to −231 , and integers larger than 231 − 1 should be fixed to 231 − 1 .
Returns integers as the final result.

Notice:

The blank characters in this question include only space characters ' ' 。
Except for the leading space or number, the rest of the string,Do not ignore it Any other character。
 
Example 1:
 
enter:s = "42"
Output:42
explain:The bold string is a character that has been read.,The caret is the currently read character。
The 1 step:"42"(No characters are read in at present,Because there are no leading spaces)
         ^
The 2 step:"42"(No characters are read in at present,Because it doesn't exist here '-' or '+')
         ^
The 3 step:"42"(Read in "42")
           ^
Analyze the integer 42 。
because "42" In range [-231, 231 - 1] Inside,The final result is 42 。
Example 2:
 
enter:s = "   -42"
Output:-42
explain:
The 1 step:"   -42"(Read into leading spaces,But ignore it)
            ^
The 2 step:"   -42"(Read in '-' character,So the result should be a negative number)
             ^
The 3 step:"   -42"(Read in "42")
               ^
Analyze the integer -42 。
because "-42" In range [-231, 231 - 1] Inside,The final result is -42 。
Example 3:
 
enter:s = "4193 with words"
Output:4193
explain:
The 1 step:"4193 with words"(No characters are read in at present,Because there are no leading spaces)
         ^
The 2 step:"4193 with words"(No characters are read in at present,Because it doesn't exist here '-' or '+')
         ^
The 3 step:"4193 with words"(Read in "4193";Since the next character is not a number,所以Read in停止)
             ^
Analyze the integer 4193 。
because "4193" In range [-231, 231 - 1] Inside,The final result is 4193 。
Example 4:
 
enter:s = "words and 987"
Output:0
explain:
The 1 step:"words and 987"(No characters are read in at present,Because there are no leading spaces)
         ^
The 2 step:"words and 987"(No characters are read in at present,Because it doesn't exist here '-' or '+')
         ^
The 3 step:"words and 987"(Due to the current character 'w' Not a number,So read in and stop)
Example 5:

enter:s = "-91283472332"
Output:-2147483648
explain:
The 1 step:"-91283472332"(No characters are read in at present,Because there are no leading spaces)
         ^
The 2 step:"-91283472332"(Read in '-' character,So the result should be a negative number)
          ^
The 3 step:"-91283472332"(Read in "91283472332")
                     ^
Analyze the integer -91283472332 。
because -91283472332 Less than range [-231, 231 - 1] The lower boundary of,The final result is truncated as -231 = -2147483648 。
 

Tip:

0 <= <= 200 s consists of English letters (upper and lower case), numbers (0-9), ' ', '+', '-' and '.'
Passed 323,466 Submitted 1,494,392

A little idea

I just saw this question (in my mind, it is definitely difficult for a good guy to write the topic so often, and I don’t want to write it). I wonder if you think so, hahaha. After reading carefully, if you read the previous example questions, this question is like Zhang Fei eating bean sprouts - a piece of cake, so everyone knows the importance of practicing the questions together. If you don’t believe it, let’s look down to verify whether it is all the methods you did before.

Start working
A general introduction to a function

The previously introduced StringBuilder() and toCharArray() are both used here. The function I will introduce to you today is the Math function. It has a wide range of application as a mathematical function. Let's take a look at what functions it has.

 Recorded pi
 RecordeConstant
Math中还有一些类似Constant,All are common engineering mathematics。
 Find the absolute value
 Sine function  反Sine function
 Cosine function  反Cosine function
 Tangent function  反Tangent function Math.atan2 商的反Tangent function
 Convert radians into angles  Angle converted to radians
[color=red] Get the maximum integer not less than a certain number A larger number than it[/color]
[color=red] Get the maximum integer no greater than a certain number A smaller number than it[/color]
 Ask for rest
 Find the largest of the two numbers
 Find the smallest of two numbers
 Please give me a prescription
[color=red] Find any power of a certain number, Throw outArithmeticExceptionHandle overflow exceptions[/color]
 begeAny power of
Math.log10 by10Logarithm at base
 Natural logarithm
 beg距离某数最近的整数(Probably larger than some,Maybe smaller than it)
[color=red] beg距离某数最近的整数,returnintType orlongtype(上一个函数returndoubletype)[/color]
 return0,1A random number between

Source code and analysis

public class test {
	public static String myAtoi(String s) {
		char[] list=();
		StringBuilder lis=new StringBuilder();
		for(int i=0;i<;i++) {
			if(list[i]==' ') {
				continue;
			}
			else if(list[i]=='+'||list[i]=='-'||((list[i])>=48&&(list[i])<=57)) {
				(list[i]);
			}else {
				return ();
			}
		}
		return ();
	}
	public static void main(String[] args) {
		long a=(myAtoi("words and 987")==""? "0":myAtoi("words and 987"));
		int b= (int) ((a, (2, 31)-1), (-2, 31));
		(b);
		
	}

}

Of course, this is written in my own format, and it does not follow the official format. Come on, let's start explaining one by one:

public static String myAtoi(String s) {
		//The following two lines are what I mentioned earlier to turn a string into a character array		char[] list=();
		StringBuilder lis=new StringBuilder();
		//The following mainly uses character length as the number of times to convert characters into integers		for(int i=0;i&lt;;i++) {
		//According to the question requirements, start to encounter spaces and discard useless leading spaces			if(list[i]==' ') {
			//I won't introduce the function of continue, it's basic.				continue;
			}//The following judgment is introduced in detail below			else if(list[i]=='+'||list[i]=='-'||((list[i])&gt;=48&amp;&amp;(list[i])&lt;=57)) {
				(list[i]);
			}else {//If you encounter characters other than the above conditions, you will end directly and return to the string				return ();
			}
		}
		return ();
	}

else if(list[i]=='+'||list[i]=='-'||((list[i])&gt;=48&amp;&amp;(list[i])&lt;=57)) {
				(list[i]);

This part is to judge + and - and the ascll value of each character. () is the function to calculate the ascll value, as long as the number between 0-9 is satisfied.

  • Actually, it should be written directly in this form
else if(list[i]=='+'||list[i]=='-'||(list[i]>='0'&&list[i]<='9')) {
				(list[i]);

Then we have the main function part left. All this part needs to be changed when submitting it, but I did not use it in the official format when writing the explanation.

public static void main(String[] args) {
//The three-point operation is involved, but we have talked about the rules before. The main function here is to prevent the following situation from returning to a null character, so we will turn it to zero  long a=(myAtoi("words and 987")==""? "0":myAtoi("words and 987"));
  //This is the main usage of the Math function mentioned above, because the answer must be judged by the scope  //So let us first find the number sum of the upper bound (2^31)-1 to find the smallest  //Compare with -2^31 to find the largest number. We are looking for. If you don’t understand, you can send a private message or comment for detailed explanation.  int b= (int) ((a, (2, 31)-1), (-2, 31));
  (b);

Well, that’s all for today’s algorithm problems. Have you learned it? In general, this question recalls our previous questions. If you don’t remember them, it is recommended to take a look. You must not forget what you have learned.

This is the article about practicing Java functions and algorithms every day, summarizing and converting integers in strings. For more related Java functions and algorithm content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!