【发布时间】:2020-05-06 05:26:16
【问题描述】:
以下代码是一种使用递归将 String 转换为 Integer 的方法。我理解了这个过程,但无法弄清楚我们这样做时会发生什么:
str.charAt(0) - '0'
我们可以使用 parseInt 或 parseDouble 轻松地将其转换为 int 或 double。那我们为什么要从字符串(一个数字)中减去一个字符“0”?这如何将我们的字符转换为 int 或 double?
// Java implementation of the approach to convert a String to an Integer using Recursion
public class GFG {
// Recursive function to convert string to integer
static int stringToInt(String str)
{
// If the number represented as a string
// contains only a single digit
// then returns its value
if (str.length() == 1)
return (str.charAt(0) - '0');
// Recursive call for the sub-string
// starting at the second character
double y = stringToInt(str.substring(1));
// First digit of the number
double x = str.charAt(0) - '0';
// First digit multiplied by the
// appropriate power of 10 and then
// add the recursive result
// For example, xy = ((x * 10) + y)
x = x * Math.pow(10, str.length() - 1) + y;
return (int)(x);
}
// Driver code
public static void main(String[] args)
{
String str = "1235";
System.out.print(stringToInt(str));
}
}
【问题讨论】:
-
看这个:
'5' - '0'...它等于5