Given a number num, write a C++ Program to find the sum of digits of the number.
Example: Input: num = 1432 Output: 10 Explanation: 1 + 4 + 3 + 2 = 10 Input: num = 9831 Output: 21 Explanation: 9 + 8 + 3 + 1 = 21
There are multiple ways to solve this problem, let's understand each of them one by one:
Approach 1: Using the modulo operator and while loop.
Follow the below steps to sum the digits of a number:
- Use a while loop to continuously extract the last digit of the number using the modulo operator (%).
- Add the extracted digit to a running total (sum), and then remove it from the number using the division (/) operator.
- This process continues until the number becomes zero.
C++ Program sums the digits of a number.
//C++ Program to sum the digits of a number #include <iostream> using namespace std; int main() { int num, sum = 0; cout << "Enter a number: "; cin >> num; while (num > 0) { sum += num % 10; num /= 10; } cout << "Sum of digits: " << sum << endl; return 0; }
Enter a number: 1345
Sum of digits: 13
- Time Complexity: O(n)
- Space Complexity: O(1)
Approach 2: Using String Streams.
Follow the below steps:
- Use a string stream to convert the integer number into a string.
- Use a for loop to iterate over each character in the string and add its integer value (obtained by subtracting the ASCII value of the character '0') to a running total (sum).
- Print the value of the sum as an output.
C++ code implementation of the above approach.
//C++ code implementation for finding sum of diigts of a num #include <iostream> #include <sstream> using namespace std; int main() { int num, sum = 0; cout << "Enter a number: "; cin >> num; stringstream ss; ss << num; string str = ss.str(); for (char c : str) { sum += c - '0'; } cout << "Sum of digits: " << sum << endl; return 0; }
Output:
Enter a number: 1349
Sum of digits: 17
- Time Complexity: O(n)
- Space Complexity: O(n)
No comments:
Post a Comment