如何在java中对整数的数字求和? [英] How to sum digits of an integer in java?

查看:27
本文介绍了如何在java中对整数的数字求和?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难找到这个问题的解决方案.我正在尝试用 Java 开发一个程序,该程序采用一个数字,例如 321,并找到数字的总和,在本例中为 3 + 2 + 1 = 6.我需要任何三位数的所有数字将它们加在一起,并使用 % 余数符号存储该值.这让我很困惑,我很感激任何人的想法.

I am having a hard time figuring out the solution to this problem. I am trying to develop a program in Java that takes a number, such as 321, and finds the sum of digits, in this case 3 + 2 + 1 = 6. I need all the digits of any three digit number to add them together, and store that value using the % remainder symbol. This has been confusing me and I would appreciate anyones ideas.

推荐答案

public static void main(String[] args) {
        int num = 321;
        int sum = 0;
        while (num > 0) {
            sum = sum + num % 10;
            num = num / 10;
        }
        System.out.println(sum); 
}

输出

6

这篇关于如何在java中对整数的数字求和?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆