code.cpp 962 B

12345678910111213141516171819202122232425262728
  1. /* A number is narcissistic when the sum of its digits, with each digit
  2. * raised to the power of digits quantity, is equal to the number itself.
  3. * 153 ➞ 3 digits ➞ 1³ + 5³ + 3³ = 1 + 125 + 27 = 153 ➞ Narcissistic
  4. * 84 ➞ 2 digits ➞ 8² + 4² = 64 + 16 = 80 ➞ Not narcissistic
  5. * Given a positive integer n, implement a function that returns true if the number is narcissistic,
  6. * and false if it's not.
  7. * Trivially, any number in the 1-9 range is narcissistic
  8. * and any two-digit number is not.
  9. * Curious fact: Only 88 numbers are narcissistic.
  10. */
  11. int powz (int base, int exp){
  12. int temp = 1;
  13. for(int i=0;i<exp;i++){
  14. temp *= base;
  15. }
  16. return temp;
  17. }
  18. bool isNarcissistic(int n) {
  19. // convert int to string to access each digit of the int
  20. std::string number = std::to_string(n);
  21. int sum = 0;
  22. for(int i=0;i<number.size();i++){
  23. int thisDigit = number[i] - '0';
  24. sum += powz(thisDigit,number.size());
  25. }
  26. return sum == n;
  27. }