將字符串轉成整數的函數給我看一下嗎,簡單看一下代碼基本功。要求:不要調用parseInt等轉換函數
阿新 • • 發佈:2018-10-17
main 一段 ack substr date tin || parse pre
為了提高面試流程效率,方便用java寫一段將字符串轉成整數的函數給我看一下嗎,簡單看一下代碼基本功。
要求:不要調用parseInt等轉換函數。按位讀取字符串裏的字符進行處理將字符串轉化為整數,
不考慮整數溢出問題,給定的輸入一定是合法輸入不包含非法字符,字符串頭尾沒有空格,
考慮字符串開頭可能有正負號。public int StringToInt(String str)
import javax.net.ssl.SSLContext; /** * 字符串轉為int * @author IT * @Date 2018年10月16日 */ public class StringToInt { public static void main(String[] args) { String s = "2018"; try { System.out.println("轉換結果"+parse(s)); } catch (Exception e) { e.printStackTrace(); } } public static int parse(String s) throws Exception{ int result = 0; if (s == null || s.length() == 0) { throw new Exception("字符串為空"); } String s1 = s; // if(s.startsWith("-")) { // s1 = s.substring(1, s.length()); // } for (int i = 0; i < s1.length(); i++) { if (i==0) { if(s1.charAt(i) == ‘-‘ ){ continue; } }else{ if(s1.charAt(i)>‘9‘ || s1.charAt(i)<‘0‘){ throw new Exception("字符串格式錯誤"); } } result = result * 10; result = ( result + s1.charAt(i) ) - ‘0‘; System.out.println("每一位數:"+s1.charAt(i)); System.out.println("每一次累加結果:"+result); } return result; } }
將字符串轉成整數的函數給我看一下嗎,簡單看一下代碼基本功。要求:不要調用parseInt等轉換函數