Summing int digits in an interger

04 November 2011
Write a method that computes the sum of the digits in an interger. Use the following method header:

public static int sumDigits(long n)


For example, sumDigits(234) return 9 (2 + 3 + 4).

Input:
234

Output:
9

Main.java

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package summingthedigitsinaninterger;

import java.util.Scanner;

/**
 *
 * @author dekwan
 */
public class Main
{

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args)
    {
        // TODO code application logic here
        Scanner scan = new Scanner(System.in);
       
        long number = scan.nextInt();
        sopl(sumDigits(number) + "\n");
    }

    public static void sopl(String str)
    {
        System.out.println(str);
    }

    public static int sumDigits(long digit)
    {
        int num;
        int sum = 0;
       
        while (digit != 0)
        {
            num = (int) digit % 10;
            digit = digit / 10;
            sum = sum + num;
        }

        return sum;
    }

}


0 comments:

Catat Ulasan

Terima kasih kerana memberi ulasan...