Counting Fancy Numbers

You are given a range of integers [l, r]. An integer is "Good" if its digits are strictly increasing (e.g., 123) or strictly decreasing (e.g., 980). Single digits (0-9) are always Good. An integer is "Fancy" if it is Good, OR if the sum of its digits is Good.

Return the total number of Fancy integers within the range [l, r].

Example 1:

Input: l = 8, r = 10

Output: 3

Explanation: We evaluate each integer in the range. The numbers 8 and 9 are single-digit integers, which are inherently strictly monotone, making them good and therefore fancy. The number 10 consists of the digits [1, 0], which form a strictly decreasing sequence. Because 10 is good, it is also fancy. Since all three numbers satisfy the conditions, the total count is 3.

Example 2:

Input: l = 12340, r = 12341

Output: 1

Explanation: For the first number 12340, the digits [1, 2, 3, 4, 0] are not strictly monotone. However, its digit sum is 1 + 2 + 3 + 4 + 0 = 10. The sum 10 has digits [1, 0] which form a strictly decreasing sequence, making the sum good and therefore the original number fancy. For the next number 12341, the digits [1, 2, 3, 4, 1] are also not strictly monotone. Its digit sum is 1 + 2 + 3 + 4 + 1 = 11. The sum 11 has digits [1, 1], which are flat and do not form a strictly increasing or decreasing sequence. Since 12341 fails both checks, it is not fancy, leaving us with exactly 1 fancy integer in this range.

Now Your Turn!

Pick the correct output for the given input

Input: l = 8, r = 20

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • 1 <= l <= r <= 1015

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

0
class Solution {
public:
long long countFancyNumbers(long long l, long long r) {
// Write your code here
}
};
Test Case

Input:

L
R