Why is the addition slower than the mod


  • 0
    G

    I have two solutions:
    one takes 4ms

        public List<String> fizzBuzz(int n) {
            List<String> res = new ArrayList<>();
            for (int i = 1, fizz = 1, buzz = 1; i <= n; i++, fizz++, buzz++) {
                if ((fizz == 3) && (buzz == 5)) {
                    res.add("FizzBuzz");
                    fizz = 0;
                    buzz = 0;
                } else if (fizz == 3) {
                    res.add("Fizz");
                    fizz = 0;
                } else if (buzz == 5) {
                    res.add("Buzz");
                    buzz = 0;
                } else {
                    res.add(String.valueOf(i));
                }
            }
            return res;
        }
    }
    

    another takes 3ms

    public class Solution {
        public List<String> fizzBuzz(int n) {
            List<String> res = new ArrayList<>();
            for (int i = 1; i <= n; i++) {
                if ((i % 3 == 0) && (i % 5 == 0)) {
                    res.add("FizzBuzz");
                } else if (i % 3 == 0) {
                    res.add("Fizz");
                } else if (i % 5 == 0) {
                    res.add("Buzz");
                } else {
                    res.add(String.valueOf(i));
                }
            }
            return res;
        }
    }
    

    why?


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.