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

查看:117
本文介绍了如何在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天全站免登陆