【问题标题】:What happens when we subtract a char integer from another char integer?当我们从另一个 char 整数中减去一个 char 整数时会发生什么?
【发布时间】: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

标签: java recursion


【解决方案1】:

'0' 的 ASCII 是 48,'1' 是 49 直到 '9' 是 57,所以通过从 '0' 中减去数字字符,您将得到十进制数ASCII_Table

【讨论】:

    猜你喜欢
    • 2015-03-01
    • 2021-02-01
    • 2022-07-31
    • 2011-07-16
    • 1970-01-01
    • 2020-08-12
    • 2023-03-16
    • 1970-01-01
    • 2020-10-22
    相关资源
    最近更新 更多