Hi 👋, I'm a software engineer specializing in backend systems, distributed systems, and scalable architecture. My blog shares practical tutorials based on 3+ years of experience. LeetCode 1756 (Top 10%). Actively seeking SDE roles — let's get in touch!
Comments
Leave a Comment
Success!
Receive Latest Updates 📬
Get every new post, special offers, and more via email. No fee required.
Sum of digits is a common problem where given a number, you need to find the sum of digits of that number.
It seems to be a basic problem, but very useful in some contexts. This tutorial will help you to solve this problem, let's get started!
#include <stdc++.h>using namespace std;int main() { int num; cout << "Enter a number: "; cin >> num; int sum = 0; while (num != 0) { sum += num % 10; num /= 10; } cout << "Sum of digits: " << sum << '\n'; return 0;}
import java.util.Scanner;public class Main { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter a number: "); int num = input.nextInt(); int sum = 0; while (num != 0) { sum += num % 10; num /= 10; } System.out.println("Sum of digits: " + sum); }}
const readline = require("readline").createInterface({ input: process.stdin, output: process.stdout});readline.question("Enter a number: ", (num) => { let sum = 0; while (num != 0) { sum += num % 10; num = Math.floor(num / 10); } console.log("Sum of digits:", sum); readline.close();});
Output:
console
Enter a number: 21032002Sum of digits: 10
In this example, the given number is 21032002, so the sum of digits is 2 + 1 + 0 + 3 + 2 + 0 + 0 + 2 = 10.
Similar to the previous method, we will use recursion to loop through the digits of the number. Here's how it works:
Define a recursive function sumOfDigits that takes an integer num as input.
Base case: If num is less than 10, return num as the sum of digits.
Recursive case: Calculate the sum of digits of num by adding the last digit (obtained using the modulo operator) to the sum of digits of the remaining digits (obtained using integer division).
def sumOfDigits(num): if num < 10: return num return num % 10 + sumOfDigits(num // 10)num = int(input('Enter a number: '))print('Sum of digits: ', sumOfDigits(num))
Another quick and efficient way:
num = int(input('Enter a number: '))print('Sum of digits: ', sum(map(int, str(num))))
import java.util.Scanner;public class Main { public static int sumOfDigits(int num) { if (num < 10) { return num; } return num % 10 + sumOfDigits(num / 10); } public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter a number: "); int num = input.nextInt(); System.out.println("Sum of digits: " + sumOfDigits(num)); }}
Maybe you know or not, but such simple task like sum of digits is very useful in some contexts:
Validating credit card numbers: The sum of digits of a credit card number can be used to check its validity.
Checking divisibility: The sum of digits of a number can be used to determine if it is divisible by a certain number, for example, a number is divisible by 3 if the sum of its digits is divisible by 3.
Cryptography: The sum of digits can be used in cryptographic algorithms to generate secure keys.
The Luhn algorithm is a simple checksum formula used to validate a variety of identification numbers, such as credit card numbers, IMEI numbers, National Provider Identifier numbers in the US, and Canadian Social Insurance Numbers. To learn more about the Luhn algorithm, you can read this article.
In the scope of this tutorial, we will learn how to use the Luhn algorithm to validate a simple 16-digit credit card number. Here's how it works:
Multiply every digit in odd positions (1st, 3rd, 5th, ...) by 2.
If the result of the multiplication is greater than 9, subtract 9 from it (or equivalently, add the two digits of the result).
Add all the digits together.
If the sum is divisible by 10, the number is valid.
Comments