Topic:
Implement atoi to convert a string to an integer.
Hint: Carefully consider all possible input cases. If you want a challenge, please don't see below and ask yourself what is the possible input cases.
Notes: It is intended for the problem to be specified vaguely (ie, no given input specs). You is responsible to gather all the input requirements up front.
Test instructions
Implements Atoi, converting a string to an integer.
Take care to consider all possible scenarios.
Algorithm Analysis:
1. Remove the extra space characters first, starting with the first non-whitespace character.
2. Read the numbers sequentially and end if the following three cases occur:
2.1 Exception characters appear (exception characters skip).
2.2 Digits out of bounds (returns the nearest integer).
2.3 End of string
Look directly at the code, no difficulty.
AC Code:
public class Solution {public int myatoi (String str) { int max = Integer.max_value; int min =-integer.min_value; Long result = 0; str = Str.trim (); int len = Str.length (); if (Len < 1) return 0; int start = 0; Boolean neg = false;//indicates positive and negative if (str.charat (start) = = '-' | | | Str.charat (START) = = ' + ') { if (Str.charat (star t) = = '-') neg = true; start++; } for (int i = start; i < Len; i++) { char ch = str.charat (i); if (Ch < ' 0 ' | | ch > ' 9 ') break ; result = Ten * result + (CH-' 0 '); if (!neg && result > Max)//exceeds the boundary, returns the boundary value directly to Max; if (Neg &&-result < min) return min; } if (neg) result =-result; return (int) result;} }
Copyright NOTICE: This article is the original article of Bo Master, reprint annotated source
[Leetcode] [Java] String to Integer (atoi)