整数的各位数字之和

huangapple go评论73阅读模式
英文:

sum of digits of an integer

问题

以下两种方法是有效的。

public static int sumInt(int num) {
    int sum;
    for (sum = 0; num != 0; num = num/10) {
        sum += num % 10;
    }
    return sum;
}


public static int sumInt(int num) {
    int sum = 0;
    while (num != 0) {
        sum+= num%10;
        num = num/10;
    }
    return sum;
}

但我想知道是否可以做一些操作,使程序将输入读取为字符串,然后使用charAt()检查字符串的每个索引,然后从每个索引处减去 '0',然后将所有这些相加。这可能不是很高效,但是可以吗?以下是我目前的代码,但还不完全正确。

import java.util.Scanner;

public class SumDigitsString {
    public static void main (String[] args ) {
        Scanner input = new Scanner (System.in);

        System.out.print("Enter an integer: ");
        String number = input.next();
        System.out.println("\nThe sum of the digits of " + number + " is " + sumInt(number));
    }   

    public static int sumInt(String num) {

        int sum = 0;

        for (int i = 0; i < num.length(); i++)
            sum += num.charAt(i) - '0';

        return sum;
    }
}
英文:

The following two methods work.

public static int sumInt(int num) {
    int sum;
    for (sum = 0; num != 0; num = num/10) {
	    sum += num % 10;
	}
    return sum;
}

and

public static int sumInt(int num) {
    int sum = 0;
    while (num != 0) {
        sum+= num%10;
        num = num/10;
    }
    return sum;
}

But I was wondering about doing something where the program reads the input as a string and then uses charAt() to check each index of the string then subtract '0' from each and add those all together. It probably is not as efficient, but can it be done? Here is what I have so far but it's not quite right:

import java.util.Scanner;

public class SumDigitsString {
    public static void main (String[] args ) {
	    Scanner input = new Scanner (System.in);
	
	    System.out.print(&quot;Enter an integer:  &quot;);
	    String number = input.next();
        System.out.println(&quot;\nThe sum of the digits of &quot; + number + &quot; is &quot; + sumInt(number));
    }   

    public static String sumInt(String num) {

        int sum = 0;

        while (num.length() - num.charAt() &gt; 0)
        sum += (num.charAt(num.length())) + &#39;0&#39;;
        num.charAt()++;
        return sum;
    }
}

答案1

得分: 1

以下是翻译好的部分:

你可以做的是这样的:

public static int sumInt(String num) {
  int sum = 0;
  for (int i = 0; i<num.length(); i++)
    sum += num.charAt(i) - '0';
  return sum;
}

如果你取出索引 i 处的字符并减去 '0',就会得到字符的值,根据 ASCII 表,当你将它添加到 sum 中时,它会在隐式转换为整数。

英文:

What you can do is this:

public static int sumInt(String num) {
  int sum = 0;
  for (int i = 0; i&lt;num.length(); i++)
    sum += num.charAt(i) - &#39;0&#39;;
  return sum;
}

If you take the character at index i and subtract '0', you get the value of the character as per the ASCII table and it then gets converted implicitly into an interger when you add it to sum.

答案2

得分: 0

你可以按以下方式完成:

public static int sumInt(String num) {
    int sum = 0, i = 0;
    while (i < num.length()) {
        char ch = num.charAt(i);
        if (Character.isDigit(ch)) {
            sum += ch - '0';
            i++;
        } else {
            throw new IllegalArgumentException(num + " 不是一个整数。");
        }
    }
    return sum;
}

一个示例运行:

输入一个整数1234

1234 的各位数字之和为10

另一个示例运行:

输入一个整数12a34
Exception in thread "main" java.lang.IllegalArgumentException: 12a34 不是一个整数
    at Main.sumInt(Main.java:20)
    at Main.main(Main.java:9)

思路是将每个数字的数值添加到一个变量(在上面给出的代码中为 sum)中,该变量初始化为 0。请注意,还重要的是要检查字符是否为数字,如果不是数字则抛出异常。

字符 &#39;0&#39; 的 ASCII 值为 48,因此要获取字符 &#39;0&#39; 的数值,需要从 &#39;0&#39;48 中减去。类似地,字符 &#39;1&#39; 的 ASCII 值为 49,因此要获取字符 &#39;1&#39; 的数值,需要从 &#39;0&#39;48 中减去。总之,为了获取数字字符的数值,我们需要从中减去 &#39;0&#39;48

英文:

You can do it as follows:

public static int sumInt(String num) {
      int sum = 0, i = 0;
      while (i &lt; num.length()) {
            char ch = num.charAt(i);
            if (Character.isDigit(ch)) {
                  sum += ch - &#39;0&#39;;
                  i++;
            } else {
                  throw new IllegalArgumentException(num + &quot; is not a whole number.&quot;);
            }
      }
      return sum;
}

A sample run:

Enter an integer:  1234

The sum of the digits of 1234 is 10

Another sample run:

Enter an integer:  12a34
Exception in thread &quot;main&quot; java.lang.IllegalArgumentException: 12a34 is not a whole number.
	at Main.sumInt(Main.java:20)
	at Main.main(Main.java:9)

The idea is to add the numeric value of each digit to a variable (sum in the code given above) initialized with 0. Note that it's also important to check if the character is a digit and throw some exception if it is not.

The ASCII value of &#39;0&#39; is 48 and therefore to get the numeric value of &#39;0&#39;, you need to subtract &#39;0&#39; or 48 from &#39;0&#39;. Similarly, The ASCII value of &#39;1&#39; is 49 and therefore to get the numeric value of &#39;1&#39;, you need to subtract &#39;0&#39; or 48 from &#39;1&#39;. In summary, in order to get the numeric value of a digit character, we need to subtract &#39;0&#39; or 48 from it.

答案3

得分: 0

Umm, 为什么不直接使用 nextInt() 呢?我认为依赖于 Java 库(这些库经过社区的试验和测试)总是比自己重写代码要好 整数的各位数字之和

Scanner input = new Scanner(System.in);
System.out.println("输入一个整数:");
int number = input.nextInt();
// 调用你之前的 sumInt(int) 方法
System.out.println("\n" + number + " 的各位数字之和是 " + sumInt(number));

我认为你没有正确使用 charAt。我不认为 num.charAt()++ 语法上是正确的。你应该像这样做:

public static int sumInt(String num) {
    int sum = 0;
    for (int i = 0; i < num.length(); i++) {
        sum += (num.charAt(i) - '0');
    }
    return sum;
}
英文:

Umm, why don't you just use nextInt() instead? I think it's always better to rely on Java libraries(which are always tried and tested by community) rather than rewriting code yourself 整数的各位数字之和

Scanner input = new Scanner(System.in);
System.out.println(&quot;Enter an integer: &quot;);
int number = input.nextInt();
// Call your old sumInt(int) method 
System.out.println(&quot;\nThe sum of the digits of &quot; + number + &quot; is &quot; + sumInt(number));

I think you're not using charAt properly. I don't think num.charAt()++ is even sytaxwise correct. You should do something like this:

public static int sumInt(String num) {
    int sum = 0;
    for (int i = 0; i &lt; num.length(); i++) {
        sum += (num.charAt(i) - &#39;0&#39;);
    }
    return sum;
}

huangapple
  • 本文由 发表于 2020年10月15日 00:59:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/64358157.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定