[Leetcode series] string to INTEGER (atoi)

Source: Internet
Author: User

Then I went directly to the Code. At first I counted "ABC123" as legal. Later I checked the definition of atoi and removed it.

Public class solution {public static int atoi (string instr) {long result = 0l;/** check it online. The definition of atoi function is that if the first non-space character exists, if it is a number or plus or minus sign, type conversion starts. * If it detects a non-digit (including the terminator \ 0) character, the conversion is stopped and the integer number is returned. Otherwise, zero is returned. Possible inputs include: 1. Empty strings * 2, "123abc", "1a2b3c", "ABC123", "-123abc" 3. Overflow 4. Spaces * // Step 1: filter space instr = instr. trim (); char [] inchararray = instr. tochararray (); int Index = 0; // step2: Positive and Negative char flag = '+ '; if (inchararray [0] = '+' | inchararray [0] = '-') {flag = inchararray [0]; Index = 1;} // Step 3: conversion and various judgments for (INT I = index; I <inchararray. length; I ++) {If (character. isdigit (inchararray [I]) {result = Result * 10 + integer. parseint (inchararray [I] + "") ;}else {break ;}// step4: If (flag = '-') {result =-result;} // step5: whether to overflow if (result> integer. max_value) {result = integer. max_value;} else if (result <integer. min_value) {result = integer. min_value;} return (INT) result;} public static void main (string [] ARGs) {// system. out. println (integer. max_value + "" + integer. min_value); string [] testcase = {"123abc", "+ 123abc", "-123abc", "123abc", "ABC123", "1ab2c3", "2222222222 ", "-2222222222"}; For (string test: testcase) {system. out. print (atoi (TEST); system. out. println ();}}}



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.