java - 将字符串转换为数字的输出不符合预期

标签 java string

Given a string as input, convert it into the number it represents. You can assume that the string consists of only numeric digits. It will not consist of negative numbers. Do not use Integer.parseInt to solve this problem.

我的方法

我将字符串转换为字符数组并存储了原始数字,但无法将其转换为单个数字 我尝试转换单个元素,但数字可以是任意长度。因此,很难遵循这种方法。

提示:我有一个提示,可以使用位值添加数字

例如,如果数字是 2300。我将每个数字以数组的形式存储。那么它应该是 2*1000+3*100+0*10+0=2300

但我无法将其转换为代码。

Can anyone guide me how to do that?

注意我不能使用任何内置函数。

public int toNumber(String str)
{
   char ch1[]=str.toCharArray();
   int c[]=new int[ch1.length];
   int k=0;
   for(int i=0;i<c.length;i++)
   {
     if(ch1[i]==48) 
     {
        c[k++]=0;
     }
     else if(ch1[i]==49)
     {
        c[k++]=1;
     }
     else if(ch1[i]==50)
     {
        c[k++]=2;
     }
     else if(ch1[i]==51)
     {
        c[k++]=3;
     }
     else if(ch1[i]==52)
     {
        c[k++]=4;
     }
     else if(ch1[i]==53)
     {
        c[k++]=5;
     }
     else if(ch1[i]==54)
     {
        c[k++]=6;
     }
     else if(ch1[i]==55)
     {
        c[k++]=7;
     }
     else if(ch1[i]==56)
     {
        c[k++]=8;
     }
     else if(ch1[i]==57)
     {
        c[k++]=9;
     }

   }
 }

最佳答案

您不需要做幂或跟踪您的乘数。每次添加一个新数字时,只需将您的总计乘以 10。并使用 c - '0' 将字符转换为数字:

int n = 0;
for (int i = 0; i < str.length(); i++) {
    n = n * 10 + str.charAt(i) - '0';
}

例如对于 1234 来说

0 * 10   + 1 = 1
1 * 10   + 2 = 12
12 * 10  + 3 = 123
123 * 10 + 4 = 1234

关于java - 将字符串转换为数字的输出不符合预期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34108292/

相关文章:

java - 在 JEditorPane java 上正确显示网站

java - 使用马拉松作为 GUI 测试

C# 从 byte[] 获取 string[]

java - Java中将字符串拆分为等长子字符串

java - 使用正则表达式仅匹配那些正确使用转义字符的字符串(根据Java语法)?

java - java中传递参数的通用可变个数

java - String.intern() 线程安全吗

Python/Numpy - 将多个一维数组写入整齐列中的文件

java - string.split(\\s+) 无法处理前导空格

java - Bean创建异常: Error creating bean with name '/' defined in ServletContext