1 問題描述
輸入一個由數字組成的字符串,請把它轉換成整數並輸出。例如,輸入字符串“123”,輸出整數123。
請寫出一個函數實現該功能,不能使用庫函數。
2 解決方案
解答本問題的基本思路:從左至右掃描字符串中的每個字符,把之前掃描得到的數字乘以10,再加上當前字符表示的數字。
但是,基本思路是這樣,還要注意以下幾點:
(1)最好判斷一下輸入是否為空。
(2)如果字符串的第一個字符是‘-’號,最終得到的整數必為負整數。
(3)輸入的字符串中不能含有不是數字的字符。
(4)輸入的字符串不能太長,否則轉換成整數后會導致整數溢出。
具體實現代碼如下:
package com.liuzhen.string_1; import java.util.Scanner; public class StringToInt { public static int Max_INT = Integer.MAX_VALUE; public static int Min_INT = Integer.MIN_VALUE; public int getStringToInt(String A){ char[] arrayA = A.toCharArray(); int n = 0; if(A.equals("") || A.equals(null)) //判斷輸入是否為空 return 0; int i = 0; while(arrayA[i] == ' ') //處理字符串首位的空格 i++; int sign = 1; //用於判定輸入字符串數字的正負,初始化為1表示為正數 if(arrayA[i] == '+' || arrayA[i] == '-'){ if(arrayA[i] == '-') sign = -1; i++; } while(i < arrayA.length && Character.isDigit(arrayA[i])){ //確定是數字0~9才執行循環 int c = arrayA[i] - '0'; //當輸入字符串表示數為正數,且大於Max_INT if(sign > 0 && (n > Max_INT/10 || (n == Max_INT/10 && c > Max_INT%10))){ n = Max_INT; break; } //當輸入字符串表示數為負數,且小於Min_INT if(sign < 0 && (n + Min_INT/10 > 0 || (n + Min_INT/10 == 0 && c + Min_INT%10 > 0))){ n = Min_INT; break; } //把之前得到的數字乘以10,再加上 當前字符表示的數字 n = n*10 + c; i++; } return sign > 0 ? n : -n; } public static void main(String[] args){ StringToInt test = new StringToInt(); Scanner in = new Scanner(System.in); System.out.println("請輸入一個由數字組成的字符串:"); String A = in.nextLine(); int result = test.getStringToInt(A); System.out.println("整數result = "+result); } }
運行結果:
請輸入一個由數字組成的字符串: -1000 整數result = -1000 請輸入一個由數字組成的字符串: +100000 整數result = 100000 請輸入一個由數字組成的字符串: a1212 整數result = 0 請輸入一個由數字組成的字符串: 1000000000000 整數result = 2147483647 請輸入一個由數字組成的字符串: -10000000000 整數result = -2147483648