I was trying to solve the following problem: https://leetcode.com/problems/add-digits/
The following method took 12ms to complete all tests:
int addDigits(int num) {
return 1+((num-1)%9);
}
whereas the following took only 8ms:
int addDigits(int num) {
return ((num-1)%9)+1;
}
Why is there such a significant difference when I add 1 at the end instead of the beginning? Should we always put constants at the end when calculating?