简体   繁体   English

Java - 将 2 个数字相加(作为字符串,不能使用 parse.int)

[英]Java - add 2 numbers together (as strings, can't use parse.int)

I need to have 2 command line arguments as 2 numbers that are strings.我需要有 2 个命令行参数作为 2 个字符串数字。 Then using a loop, add the numbers together.然后使用循环,将数字相加。 For example,例如,

Java AddStrings 123 456 Java AddStrings 123 456

The sum is: 579总和为:579

It's for an assignment in class, having trouble figuring out what the loop would be.这是课堂作业,无法弄清楚循环是什么。 I can't just convert the strings to integers using parse.Int either.我也不能只使用 parse.Int 将字符串转换为整数。 Any ideas?有任何想法吗?

Basically you find the length of the string.基本上你会找到字符串的长度。 Loop over each individual character (I would start at the end of the string and work backwards).循环遍历每个单独的字符(我会从字符串的末尾开始并向后工作)。 Then for each iteration of the loop you would take the char convert that to an int (through type casting) and add it to your total.然后对于循环的每次迭代,您将把 char 转换为 int(通过类型转换)并将其添加到您的总数中。 Each time you step make sure to multiple your number by a power of ten.每次您踏出一步时,请确保将您的数字乘以 10 的幂。 take that value then add them and then output your answer.取该值,然后将它们相加,然后输出您的答案。 (not gonna give you code cus its a homework assignment ;) ) (不会给你代码因为它是家庭作业;))

int a = Integer.valueOf(args[0]);
int b = Integer.valueOf(args[1]);

Very simple.很简单。 I found a lot just looking at Google.我发现很多只是看着谷歌。 Or:或者:

Integer i = new Integer(args[x]);

Try this one:-试试这个:-

First,you take the input.Let s1 and s2 be the 2 strings.The required loop is like this:-首先,你接受输入。让 s1 和 s2 是 2 个字符串。所需的循环是这样的:-

String ar[]={s1,s2};
int n=0;
for(int i=0;i<2;i++)
n+=Integer.parseInt(ar[i]);
System.out.println("The sum is:-"+n);

Just use "+" to add them together.只需使用“+”将它们加在一起。 I think that you are overthinking the question.我认为你是在过度思考这个问题。

  public String addStrings(String num1, String num2) {
      StringBuilder sb = new StringBuilder();
      int carry = 0;
      int i = num1.length() - 1;
      int j = num2.length() - 1;

      while (i > -1 || j > -1) {
          int sum = carry + (i < 0 ? 0 : num1.charAt(i--) - 48);
          sum += j < 0 ? 0 : num2.charAt(j--) - 48;
          sb.append(sum % 10);
          carry = sum / 10;
      }
      return sb.append(carry == 1 ? "1" : "").reverse().toString();
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM