Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit d591cf6

Browse files
Merge pull request #1 from borrelunde/string_to_integer_atoi
LeetCode problem: 8. String to Integer (atoi)
2 parents 6327f3f + e564846 commit d591cf6

File tree

3 files changed

+462
-0
lines changed

3 files changed

+462
-0
lines changed
Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
# 8. String to Integer (atoi)
2+
3+
Difficulty: `Medium`
4+
Topics: `String`
5+
6+
Implement the `myAtoi(string s)` function, which converts a string to a 32-bit signed integer (similar to C/C++'s `atoi`
7+
function).
8+
9+
The algorithm for `myAtoi(string s)` is as follows:
10+
11+
1. Read in and ignore any leading whitespace.
12+
2. Check if the next character (if not already at the end of the string) is `'-'` or `'+'`. Read this character in if it
13+
is either. This determines if the final result is negative or positive respectively. Assume the result is positive if
14+
neither is present.
15+
3. Read in next the characters until the next non-digit character or the end of the input is reached. The rest of the
16+
string is ignored.
17+
4. Convert these digits into an integer (i.e. `"123" -> 123`, `"0032" -> 32`). If no digits were read, then the integer
18+
is `0`. Change the sign as necessary (from step 2).
19+
5. If the integer is out of the 32-bit signed integer range `[-2^31, 2^31 - 1]`, then clamp the integer so that it
20+
remains
21+
in the range. Specifically, integers less than `-2^31` should be clamped to `-2^31`, and integers greater
22+
than `2^31 - 1` should be clamped to `2^31 - 1`.
23+
6. Return the integer as the final result.
24+
25+
Note:
26+
27+
- Only the space character `' '` is considered a whitespace character.
28+
- **Do not ignore** any characters other than the leading whitespace or the rest of the string after the digits.
29+
30+
**Example 1:**
31+
32+
```text
33+
Input: s = "42"
34+
Output: 42
35+
Explanation: The caret is the current reader position.
36+
Step 1: "42" (no characters read because there is no leading whitespace)
37+
^
38+
Step 2: "42" (no characters read because there is neither a '-' nor '+')
39+
^
40+
Step 3: "42" ("42" is read in)
41+
^
42+
The parsed integer is 42.
43+
Since 42 is in the range [-2^31, 2^31 - 1], the final result is 42.
44+
```
45+
46+
**Example 2:**
47+
48+
```text
49+
Input: s = " -42"
50+
Output: -42
51+
Explanation:
52+
Step 1: " -42" (leading whitespace is read and ignored)
53+
^
54+
Step 2: " -42" ('-' is read, so the result should be negative)
55+
^
56+
Step 3: " -42" ("42" is read in)
57+
^
58+
The parsed integer is -42.
59+
Since -42 is in the range [-2^31, 2^31 - 1], the final result is -42.
60+
```
61+
62+
**Example 3:**
63+
64+
```text
65+
Input: s = "4193 with words"
66+
Output: 4193
67+
Explanation:
68+
Step 1: "4193 with words" (no characters read because there is no leading whitespace)
69+
^
70+
Step 2: "4193 with words" (no characters read because there is neither a '-' nor '+')
71+
^
72+
Step 3: "4193 with words" ("4193" is read in; reading stops because the next character is a non-digit)
73+
^
74+
The parsed integer is 4193.
75+
Since 4193 is in the range [-2^31, 2^31 - 1], the final result is 4193.
76+
```
77+
78+
**Constraints:**
79+
80+
- `0 <= s.length <= 200`
81+
- `s` consists of English letters (lower-case and upper-case), digits (`0-9`), `' '`, `'+'`, `'-'`, and `'.'`.
Lines changed: 111 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,111 @@
1+
package com.bl.string_to_integer_atoi;
2+
3+
/**
4+
* This is the solution to the LeetCode problem: 8. String to Integer (atoi)
5+
*
6+
* @author Børre A. Opedal Lunde
7+
* @since 2024年01月25日
8+
*/
9+
public class Solution {
10+
11+
static final char WHITESPACE = ' ';
12+
13+
static final char PLUS = '+';
14+
static final char MINUS = '-';
15+
16+
static final int MINIMUM_VALUE = 0x80000000; // -2^31
17+
static final int MAXIMUM_VALUE = 0x7fffffff; // 2^31 - 1
18+
19+
public int myAtoi(String s) {
20+
21+
// If the string is empty, return zero.
22+
if (s.isEmpty()) {
23+
return 0;
24+
}
25+
26+
// Convert the string to a character array that we'll iterate over.
27+
final char[] characters = s.toCharArray();
28+
29+
// Used to keep track of whether the number is negative or not.
30+
boolean negative = false;
31+
32+
// This is the index used to iterate over the character array. It is
33+
// declared outside the loop so that it can be used in both loops.
34+
int i = 0;
35+
36+
// First, ignore leading whitespace and account for explicit sign
37+
// symbol.
38+
for (; i < characters.length; i++) {
39+
char character = characters[i];
40+
41+
// Ignore leading whitespace.
42+
if (character == WHITESPACE) {
43+
continue;
44+
}
45+
46+
// Account for explicit sign symbol.
47+
else if (character == PLUS) {
48+
// The number is positive by default, so we don't need to do
49+
// set the negative flag to false.
50+
51+
// Increment the index to skip the sign symbol.
52+
i++;
53+
} else if (character == MINUS) {
54+
negative = true;
55+
56+
// Same as above.
57+
i++;
58+
}
59+
60+
// If the character is not whitespace nor a sign symbol, we will
61+
// delegate the rest of the work to the next loop. It is responsible
62+
// for parsing the number.
63+
break;
64+
}
65+
66+
// We're parsing an integer, but we're using a long to avoid overflow
67+
// and underflow.
68+
long number = 0;
69+
70+
// Parse the number.
71+
for (; i < characters.length; i++) {
72+
final char character = characters[i];
73+
74+
// If the character is not a digit, we will break out of the loop.
75+
if (! characterIsDigit(character)) {
76+
break;
77+
}
78+
79+
// Convert the character to a digit.
80+
final int digit = digitFromCharacter(character);
81+
82+
// First, multiply the number by ten to make room for the new digit.
83+
// Then, add the digit to the number, taking into account whether
84+
// the number is negative or not.
85+
number = number * 10 + (negative ? - digit : digit);
86+
87+
// Clamp the number if it is greater than the maximum value.
88+
if (number <= MINIMUM_VALUE) {
89+
return MINIMUM_VALUE;
90+
}
91+
92+
// Clamp the number if it is less than the minimum value.
93+
else if (number >= MAXIMUM_VALUE) {
94+
return MAXIMUM_VALUE;
95+
}
96+
}
97+
98+
// Return the number as an integer.
99+
return (int) number;
100+
}
101+
102+
static int digitFromCharacter(final char character) {
103+
// Assumes the digit character is in the ASCII table.
104+
return character - '0';
105+
}
106+
107+
static boolean characterIsDigit(final char character) {
108+
// Assumes the character is in the ASCII table.
109+
return character >= '0' && character <= '9';
110+
}
111+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /