Hey fellow coders! Today, on Day 15 of my 100-day DSA challenge, I tackled a LeetCode problem called "Count the Good Numbers." Let me walk you through the journey.
The task was counting 'good' numbers in a given range. What's a 'good' number, you ask? It's a number made up of only 4s, 5s, and their multiples (like 4, 5, 44, 45, and so on).
To crack this challenge, I leaned on two coding buddies: Binary Exponentiation and Modular Arithmetic. These two made the seemingly complex problem a lot more manageable.
Here's a snippet of the code:
class Solution {
public:
long long mod = 1e9+7;
int expo(int a, long long b) {
if(b == 0) {
return 1;
}
long long sol = expo(a, b / 2) % mod;
if(b % 2 == 0) {
sol = (sol % mod * sol % mod) % mod;
return sol;
} else {
sol = (a % mod * sol % mod * sol % mod) % mod;
return sol;
}
}
int countGoodNumbers(long long n) {
int p = expo(20, n / 2) % mod;
if(n % 2 == 0) {
return p % mod;
} else {
return (5 % mod * p % mod) % mod;
}
}
};
I used the expo
function for quick exponentiation and made sure everything stays within bounds using modular arithmetic.
Day 15 turned out to be a dive into mathematical concepts that proved surprisingly helpful in coding. Who would've thought math could be this cool in programming?
As I continue this challenge, I'm eager to face more coding adventures. If you've got questions or just want to share your thoughts, drop a comment. Until Day 16, happy coding!