Đề bài
Viết chương trình C# tính tổng các chữ số của một số nguyên n. Ví dụ: 1234 = 1 + 2 + 3 + 4 = 10.
Lời giải
using System;
using System.Collections.Generic;
using System.Text;
namespace HelloWorld
{
class TongChuSo
{
static int DEC_10 = 10;
/**
* Tinh tong cac chu so cua mot so nguyen duong
*/
static int totalDigitsOfNumber(int n)
{
int total = 0;
do
{
total = total + n % DEC_10;
n = n / DEC_10;
} while (n > 0);
return total;
}
/**
* Ham main
*/
static void Main(string[] args)
{
int n;
Console.Write("Nhap so nguyen duong n = ");
n = Convert.ToInt32(Console.ReadLine());
Console.Write("Tong cac chu so cua {0} la: {1}", n, totalDigitsOfNumber(n));
}
}
}
Kết quả:
Nhap so nguyen duong n = 1234 Tong cac chu so cua 1234 la: 10