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?
This is not reproducible. Both versions generate exactly the same assembly code under several compilers. The output is also the same with -O3
.
Please see https://godbolt.org/g/K6PZM5
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With