LearnFrenzy
Sign in Take a free test

Basic Syntax and Data Types · Basic Programs · Question 2

Sum and reverse the digits of a number in C++ Solution, output & explanation

  • Program
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 2 Back to Exercise

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.

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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links