Leetcode8--->string to integer (convert strings to integers)

Source: Internet
Author: User

topic: Implementing String-to-integer conversions

Problem Solving Ideas:

Here are some details that should be noted in this question:

1. String "123" = 123;

2. String "+123" = 123;

3. String "123" =-123;

4. String "-" = 0; "+" = 0;

5. String "123-" = 123;

6. String "21474836478" = 2147483647 (Integer.max_value)

7. The remaining cases are illegal inputs and return 0;

The code is as follows:

1  Public classSolution {2      Public intmyatoi (String str) {3         if(str = =NULL|| Str.length () < 1)4             return0;5         BooleanNegative =false;6         inti = 0;7         Doubleres = 0.0;8String s =Str.trim ();9         intLength =s.length ();Ten         if(S.charat (i) < ' 0 '){ One             if(S.charat (i) = = '-'){ ANegative =true; -             } -             Else if(S.charat (i)! = ' + '){ the                 return0; -             } -             if(Length = = 1) -                 return0; +i++; -         } +          while(I <length) { A             intn = (S.charat (i)-' 0 ') ; at             if(n >= 0 && N <= 9){ -Res *= 10; -Res + =N; -i + +; -             } -             Else in                  Break; -  to         } +         if(negative) { -Res *=-1; the         } *res = res >= integer.max_value?Integer.MAX_VALUE:res; $res = res <= integer.min_value?Integer.MIN_VALUE:res;Panax Notoginseng         return(int) Res; -     } the}

Leetcode8--->string to integer (convert strings to integers)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.