Numerical addition in C ++

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?

+4
source share
1 answer

This is not reproducible. Both versions generate exactly the same build code in multiple compilers. The output is also the same with -O3.

See https://godbolt.org/g/K6PZM5

0
source

All Articles