1. Fizz Buzz
https://leetcode.com/explore/interview/card/top-interview-questions-easy/102/math/743/
if-else:
class Solution {public:vector<string> fizzBuzz(int n) {vector<string> result;for(int i = 1; i <= n; i++){if((i % 3 == 0) && (i % 5 == 0)){result.push_back("FizzBuzz");} else if((i % 3 == 0) && (i % 5 != 0)){result.push_back("Fizz");} else if((i % 3 != 0) && (i % 5 == 0)){result.push_back("Buzz");} else {result.push_back(to_string(i));}}return result;}};
2. Count Primes
https://leetcode.com/explore/interview/card/top-interview-questions-easy/102/math/744/
write a isPrime() approach:
class Solution {public:int countPrimes(int n) {int count = 0;for(int i = 2; i < n; i++){ //the requirement is "less than n", not including itselfif(isPrime(i)){count++;}}return count;}private:bool isPrime(int n) {if(n <= 1)return false;for(int i = 2; i * i <= n; i++){if(n % i == 0)return false;}return true;}};
3. Power of Three
https://leetcode.com/explore/interview/card/top-interview-questions-easy/102/math/745/
recursively check powers of 3:
- simple logic but a bit complicated code
-
check the remainder of fmod:
class Solution {public:bool isPowerOfThree(int n) {return fmod(log10(n)/log10(3), 1) == 0;}};
fmod() has 2 parameters, simply it returns a float value, in this case is:
% 1
is a float value here
- use
instead of
is because
- so
- it’s better for C++ to just apply log10() to finish it
4. Roman to Integer
https://leetcode.com/explore/interview/card/top-interview-questions-easy/102/math/878/
switch and go over:
class Solution {public:int roman_map(char s){switch(s) {case 'I': return 1;case 'V': return 5;case 'X': return 10;case 'L': return 50;case 'C': return 100;case 'D': return 500;case 'M': return 1000;default: return 0;}}int romanToInt(string s) {int sum = 0;for(int i = 0; i < s.size(); i++){if(i>0 && roman_map(s[i]) > roman_map(s[i-1]))sum += (roman_map(s[i]) - 2 * roman_map(s[i-1])); //need to subtract the previous oneelsesum += roman_map(s[i]);}return sum;}};+
