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