第六章第二题(求一个整数各位数字之和)(Sum the digits in an integer)

第六章第二题(求一个整数各位数字之和)(Sum the digits in an integer)

  • *6.2(求一个整数各位数字之和)编写一个方法,计算一个整数各位数字之和。使用下面的方法头:
    public static int sumDigits(long n)

    例如:sumDigits(234)返回9(2+3+4)。 提示:使用求余操作符%提取数字,用除号/去掉提取出来的数字。例如:使用234%10(=4)提取4。然后使用234/10(=23)从234中去掉4。使用一个循环来反复提取和去掉每位数字,直到所有的位数都提取完为止。 编写程序提示用户输入一个整数,然后显示这个整数所有数字的和。
    *6.2(Sum the digits in an integer) Write a method that computes the sum of the digits in an integer. Use the following method header:
    public static int sumDigits(long n)

    For example, sumDigits(234) returns 9 (= 2 + 3 + 4). (Hint: Use the % operator to extract digits and the / operator to remove the extracted digit. For instance, to extract 4 from 234, use 234 % 10 (= 4 ). To remove 4 from 234, use 234 / 10(= 2 3 ). Use a loop to repeatedly extract and remove the digit until all the digits are extracted. Write a test program that prompts the user to enter an integer then displays the sum of all its digits.

  • 参考代码:

package chapter06;

import java.util.Scanner;

public class Code_02 {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter an integer: ");
        long number = input.nextInt();
        System.out.println("The sum of the digits in an integer: " + sumDigits(number));
    }
    public static int sumDigits(long n){
        int sum = 0;
        while (n >= 10){
            sum += n % 10;
            n /= 10;
        }
        return (int)(sum + n);
    }
}

  • 结果显示:
Enter an integer: 234
The sum of the digits in an integer: 9

Process finished with exit code 0

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值