字符串整数互转
整数转为字符串
public static String intToString(int n){ String str=""; boolean isPostive = n>0?true:false; n = Math.abs(n); while(n>0){ int m=n%10; str=m+str; n=n/10; } return isPostive == true ? str : "-"+str; }
字符串转整数:
public int myAtoi(String str) { if(str == null || str.length() ==0 ) return 0; str = str.trim(); boolean isPositive = true; boolean isOverFlow = false; long res = 0; for(int i = 0 ; i < str.length(); i++) { char ch = str.charAt(i); if(i ==0 && (ch == '-' || ch == '+')) { if(ch == '-') { isPositive = false; } continue; } if(ch > '9' || ch < '0') break;//"+-2" " -0012a42" res = res * 10 + (ch - '0'); if( res > Integer.MAX_VALUE) isOverFlow = true; } res = isPositive == true ? res : -res; if( isOverFlow == true && isPositive == true ) return Integer.MAX_VALUE; else if(isOverFlow == true && isPositive == false ) return Integer.MIN_VALUE; else return (int) res; }

浙公网安备 33010602011771号