GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — leetcode/code/lc8.java at master · mJackie/leetcode Expand file tree/ Copy pathlc8.javaMore file actions 41 lines (40 loc) · 1.18 KB / Copy pathlc8.javaFile metadata and controls41 lines (40 loc) · 1.18 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 package code; /* * 8. String to Integer (atoi) * 题意:字符串转数字,按题目要求转换。(题出的不好,没什么意义) * 难度:Medium * 分类:Math, String * 注意:如何判断溢出 */ public class lc8 { public static void main(String[] args) { System.out.println(myAtoi(" -42")); } public static int myAtoi(String str) { char[] s = str.toCharArray(); int i = 0; int num = 0; int sign = 1; while( i<s.length && s[i]==' ') i++; if( i<s.length && s[i]=='+' ){ sign = 1; i++; } else if( i<s.length && s[i]=='-' ){ sign = -1; i++; } while( i<s.length && s[i]>='0' && s[i]<='9' ){ //sign 乘了两次,保证num为正,以便*10+下一位 int temp = sign * (num * 10 + Integer.parseInt(String.valueOf(s[i]))); if( sign==1 && temp/10*sign != num ) return Integer.MAX_VALUE; else if( sign==-1 && temp/10*sign != num ) return Integer.MIN_VALUE; num = temp * sign; i++; } return sign * num; } } |
| You are visitor 01402775 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |