leetcode 8. String to Integer (atoi)

来源:互联网 发布:淘宝网折800女士皮草 编辑:程序博客网 时间:2024/05/20 08:25
//Implement atoi to convert a string to an integer.//Hint: Carefully consider all possible input cases. //If you want a challenge, please do not see below and ask yourself what are the possible input cases.//Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). //You are responsible to gather all the input requirements up front. public class Solution {public static void main(String[] args) {String a = "0101231+123";int result = myAtoi(a);System.out.println(result);}public static int myAtoi(String str) {double result = 0;String s = "";int i = 0;boolean flag = false;if(str.length() == 0){//输入空串返回0return 0;}while(str.charAt(i) == ' '){//去除字符串前面的空格i++;}if(str.charAt(i) == '+'){//判断首字符是+或-i++;}else if(str.charAt(i) == '-'){i++;flag = true;}for(int j = i;j<str.length();j++){if(str.charAt(j)<='9'&&str.charAt(j)>='0'){//是数字则加入字符串s = s+str.charAt(j);}else{//如果是连续非数字则输入错误break;}}if(s.length() == 0){//连续非数字或只有一个非数字字符则返回0return 0;}result = Double.parseDouble(s);//将字符串转换为double型,防止溢出if(flag == true){result = -result;}return (int)result;//返回int    }    }

0 0
原创粉丝点击