I'm doing a simple addition with string. Which one is more efficient:
In the first one, the program will do short jump.
For the second, program may access carry 2 times.
1 2 3 4
if (r >= 10) {
carry = (r-r%10)/10;
r = r%10;
} else carry = 0;
or:
1 2 3 4 5
carry = 0;
if (r >= 10) {
carry = (r-r%10)/10;
r = r%10;
}
Ah, you were right guestgulkan!
Just realized: the maximum number in 2 numbers addition is 19, so the maximum carry should only be one. I have carry in integer so the decimal should automatically truncated...
Thank you so much.
*I've tried bool for carry and the code still works.
Another question. Which one is more efficient (now should be in memory access):
1 2 3 4 5 6 7 8
for (int j=a.size()-1; j>0; j--) { // my current code
if (a[j] == '.') continue;
short r = (a[j] - '0') * (b[i] - '0') + carry; // declaration inside the loop
carry = r/10;
r %= 10;
temp += r + '0';
}
or
1 2 3 4 5 6 7 8 9
short r = 0; // declaration outside the loop
for (int j=a.size()-1; j>0; j--) {
if (a[j] == '.') continue;
r = (a[j] - '0') * (b[i] - '0') + carry;
carry = r/10;
r %= 10;
temp += r + '0';
}
Or maybe there are any something simpler?
Can I just use char? Since the maximum number of multiplication should only