码迷,mamicode.com
首页 > 其他好文 > 详细

8. String to Integer (atoi)

时间:2020-01-04 12:21:28      阅读:77      评论:0      收藏:0      [点我收藏+]

标签:ica   tin   ==   osi   pre   har   mamicode   sign   min   

Description

技术图片

Soluction

public class Solution {
	public int myAtoi(String str) {
		char[] numbers = str.toCharArray();
		// sign symbol, 1 for positive, -1 for negative
		int sign = 1;
		// start position
		int start = -1;
		// number to return
		long sum = 0;
		// make sure only one sign symbol
		boolean signExist = false;
		// loop until find the first numerical digit
		for (int i = 0; i < numbers.length; i++) {
			char temp = numbers[i];
			if (temp == ‘ ‘) {
				if (signExist == true)
					break;
				else
					continue;
			}
			else if (temp == ‘+‘ || temp == ‘-‘) {
				if (signExist == false) {
					signExist = true;
					if (temp == ‘-‘)
						sign = -1;
					continue;
				} else {
					break;
				}
			} else if (temp >= ‘0‘ && temp <= ‘9‘) {
				if (start == -1) {
					start = i;
					break;
				}
			}
			else {
				break;
			}
		}
		
		// numerical digits don‘t exist
		if (start == -1)
			return (int)sum;
		
		
		// combine to a number 
		for (int i = start; i < numbers.length; i++) {
			if (numbers[i] >= ‘0‘ && numbers[i] <= ‘9‘) {
				sum = sum * 10 + (numbers[i] - ‘0‘);
				if (sum*sign > Integer.MAX_VALUE) {
					sum = Integer.MAX_VALUE;
					break;
				}
				if (sum*sign < Integer.MIN_VALUE) {
					sum = Integer.MAX_VALUE + 1;
					break;
				}
			} else {
				break;
			}
		}
		
		return (int)sum*sign;
	}
}

  

8. String to Integer (atoi)

标签:ica   tin   ==   osi   pre   har   mamicode   sign   min   

原文地址:https://www.cnblogs.com/codersujf/p/12148306.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!