Skip to content

Latest commit

 

History

History

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 

README.md

Given an integer n, return true if and only if it is an Armstrong number.

The k-digit number n is an Armstrong number if and only if the kth power of each digit sums to n.

 

Example 1:

Input: n = 153
Output: true
Explanation: 153 is a 3-digit number, and 153 = 13 + 53 + 33.

Example 2:

Input: n = 123
Output: false
Explanation: 123 is a 3-digit number, and 123 != 13 + 23 + 33 = 36.

 

Constraints:

  • 1 <= n <= 108

Companies:
Amazon

Related Topics:
Math

Solution 1.

// OJ: https://leetcode.com/problems/armstrong-number/
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(lgN)
class Solution {
public:
    bool isArmstrong(int n) {
        long sum = 0, target = n;
        vector<int> digits;
        while (n) {
            digits.push_back(n % 10);
            n /= 10;
        }
        for (int d : digits) sum += pow(d, digits.size());
        return sum == target;
    }
};

Solution 2.

// OJ: https://leetcode.com/problems/armstrong-number/
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(1)
class Solution {
public:
    bool isArmstrong(int n) {
        long sum = 0, cnt = log10(n) + 1, target = n;
        while (n) {
            sum += pow(n % 10, cnt);
            n /= 10;
        }
        return sum == target;
    }
};