1. Fizz Buzz

https://leetcode.com/explore/interview/card/top-interview-questions-easy/102/math/743/

if-else:

  1. class Solution {
  2. public:
  3. vector<string> fizzBuzz(int n) {
  4. vector<string> result;
  5. for(int i = 1; i <= n; i++){
  6. if((i % 3 == 0) && (i % 5 == 0)){
  7. result.push_back("FizzBuzz");
  8. } else if((i % 3 == 0) && (i % 5 != 0)){
  9. result.push_back("Fizz");
  10. } else if((i % 3 != 0) && (i % 5 == 0)){
  11. result.push_back("Buzz");
  12. } else {
  13. result.push_back(to_string(i));
  14. }
  15. }
  16. return result;
  17. }
  18. };

2. Count Primes

https://leetcode.com/explore/interview/card/top-interview-questions-easy/102/math/744/

write a isPrime() approach:

  1. class Solution {
  2. public:
  3. int countPrimes(int n) {
  4. int count = 0;
  5. for(int i = 2; i < n; i++){ //the requirement is "less than n", not including itself
  6. if(isPrime(i)){
  7. count++;
  8. }
  9. }
  10. return count;
  11. }
  12. private:
  13. bool isPrime(int n) {
  14. if(n <= 1)
  15. return false;
  16. for(int i = 2; i * i <= n; i++){
  17. if(n % i == 0)
  18. return false;
  19. }
  20. return true;
  21. }
  22. };

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
  • skip this

    check the remainder of fmod:

    1. class Solution {
    2. public:
    3. bool isPowerOfThree(int n) {
    4. return fmod(log10(n)/log10(3), 1) == 0;
    5. }
    6. };
  • fmod() has 2 parameters, simply it returns a float value, in this case is:

    • 8. Math - 图1 % 1
    • 8. Math - 图2 is a float value here
  • use 8. Math - 图3 instead of 8. Math - 图4 is because
    • 8. Math - 图5
    • so 8. Math - 图6
    • 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:

  1. class Solution {
  2. public:
  3. int roman_map(char s){
  4. switch(s) {
  5. case 'I': return 1;
  6. case 'V': return 5;
  7. case 'X': return 10;
  8. case 'L': return 50;
  9. case 'C': return 100;
  10. case 'D': return 500;
  11. case 'M': return 1000;
  12. default: return 0;
  13. }
  14. }
  15. int romanToInt(string s) {
  16. int sum = 0;
  17. for(int i = 0; i < s.size(); i++){
  18. if(i>0 && roman_map(s[i]) > roman_map(s[i-1]))
  19. sum += (roman_map(s[i]) - 2 * roman_map(s[i-1])); //need to subtract the previous one
  20. else
  21. sum += roman_map(s[i]);
  22. }
  23. return sum;
  24. }
  25. };+