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