C++ Practice Problem – ‘Narcissistic Number’ Problem 1

Time Limit: 2s Memory Limit: 192MB

Problem Description

Determine whether a number is a “Narcissistic number”. A “Narcissistic number” is defined as a three-digit number where the sum of the cubes of its digits equals the number itself. For example: 371 is a “Narcissistic number” because 371 = 3^3 + 7^3 + 1^3.

Input Format

A three-digit number

Output Format

1 or 0 (1 indicates that the number is a Narcissistic number, 0 indicates that it is not)

Sample Input

371

Sample Output

1

Code

#include <iostream>using namespace std;
int main() {    int num;    cin >> num;  // Input three-digit number
    // Decompose digits    int a = num / 100;      // Hundreds place    int b = (num / 10) % 10; // Tens place    int c = num % 10;        // Units place
    // Calculate the sum of cubes    int sum = a*a*a + b*b*b + c*c*c;
    // Check and output result    cout << (sum == num ? 1 : 0);
    return 0;}

Output Result

C++ Practice Problem - 'Narcissistic Number' Problem 1

Program Explanation:

  • Digit decomposition technique: /100 for hundreds place, /10%10 for tens place, %10 for units place
  • Use multiplication for cube calculation instead of the pow function for better efficiency
  • Concise usage of the conditional operator ?:
  • Basic usage of input and output streams

This problem is relatively simple, so no further explanation is provided.C++ Practice Problem - 'Narcissistic Number' Problem 1

C++ Basic Tutorial Collection

C++ Practice Problem - 'Narcissistic Number' Problem 1C++ Basic Resources

1. C++ Output

2. C++ Variables

3. C++ Input

4. C++ Expressions

5. IF Statements

6. IF Applications

7. WHILE Loop Statements

8. FOR Loop Statements

9. Arrays

10. One-Dimensional Arrays

11. Two-Dimensional Arrays

12. C++ Functions

13. C++ File Operations – Writing Files

If you find it useful, please click on me

C++ Practice Problem - 'Narcissistic Number' Problem 1C++ Practice Problem - 'Narcissistic Number' Problem 1C++ Practice Problem - 'Narcissistic Number' Problem 1C++ Practice Problem - 'Narcissistic Number' Problem 1

Leave a Comment