5

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?

  • I guess leetcode is measuring the time for you, but are these results reliably reprocucable? Do you always get the same numbers? Did you try other variants? E.g. something like `int result = 1;return result + ((num-1)%9);` vs `int result = ((num-1)%9);return result + 1;` vs `int result = ((num-1)%9);return 1+result;` ? – 463035818_is_not_an_ai Jun 05 '16 at 10:31
  • 2
    Please, post compiler and its arguments. I literally cannot make compilers generate different code for these functions. – Revolver_Ocelot Jun 05 '16 at 10:38
  • @tobi303 I always get the same numbers. – Chaliswaan Choor Jun 05 '16 at 11:26
  • @Nicu I am not sure what you mean. The method works because it passed all of the thousand or so tests. – Chaliswaan Choor Jun 05 '16 at 11:28
  • If you always get the same numbers actually I dont believe that your results are correct. Time measurements are always subject to uncertanties. Of course if your timer has a precision of ms, you might get the same results but I would be really surprised if you get exactly the same number each time – 463035818_is_not_an_ai Jun 05 '16 at 11:29
  • Whatever test you have deployed (and I hope that you invoked each method a sufficient number of times required in order to determine the execution times which you have specified) - reverse the order in which you are checking those two functions, in order to cancel out the **possible impact of caching heuristics used by the underlying HW architecture**, and check whether or not you get the same results. My guess is that you will get results opposite of what you have described. – barak manos Jun 05 '16 at 13:46
  • try to run again you will get difference in time about 30 to 40 ms means its time taken to read or output data.. – Ashish Chaudhary May 14 '17 at 06:41
  • I think Your question give quantum physics knowledge means if use use first test case and second test case your execution time will oscillate between 8ms to 40ms so try again ... your code will give other difference beteen time of execution... – Ashish Chaudhary May 14 '17 at 14:12

1 Answers1

1

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

Kenji
  • 726
  • 5
  • 9