LeetCode July Challenge - Day 4

Problem: LeetCode July Challenge - Day 4

Ideas

  1. An ugly number is generated by another ugly number multiplied by 2, 3 or 5, starting with 1.

Solution:

class Solution {
public:
    int nthUglyNumber(int n) {
        list<long long> ugly{1};
        list<long long>::iterator i2, i3, i5;
        i2 = i3 = i5 = ugly.begin();

        while(ugly.size() < n){
            int next = min(min((*i2)*2,(*i3)*3),(*i5)*5);
            ugly.push_back(next);
            if(next == (*i2)*2) i2++;
            if(next == (*i3)*3) i3++;
            if(next == (*i5)*5) i5++;
        }
        return ugly.back();
    }
};