Read a positive integer and print the sum of its digits and the number reversed.
Solution
main.cpp
#include <iostream>
int main() {
long long n;
std::cin >> n;
long long sum = 0, reversed = 0;
for (long long m = n; m > 0; m /= 10) {
int digit = m % 10;
sum += digit;
reversed = reversed * 10 + digit;
}
std::cout << "digit sum = " << sum << ", reversed = " << reversed << '\n';
return 0;
}
Output Verified by compiling and running
digit sum = 21, reversed = 91704
m % 10 gives the last digit and m /= 10 removes it. Building reversed as reversed × 10 + digit puts the digits back in the opposite order. long long leaves room for big inputs.
More Basic Syntax and Data Types practice questions
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!