Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numeric addition in c++

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?

like image 720
Chaliswaan Choor Avatar asked Nov 08 '22 14:11

Chaliswaan Choor


1 Answers

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

like image 104
Kenji Avatar answered Nov 15 '22 05:11

Kenji