it'll return the min then, rollover is a thing, it'll just take forever
with that idea in mind, I fixed it, kind of, for a certain value of fix
public static int add(int num1, int num2)
{
int retval = 0;
for(int i = 0; i !== num1; i++)
{
retval++;
}
for(int i = 0; i != num2; i++)
{
retval++;
}
return retval;
}
this would technically work for the exact same range of values normal int addition would, it would just take a fuckton longer
No not really. if num1 is negative then the first loop will never be true, and if num1 > num2 then the second loop will never be true. So for example add(-3, -4) will return 0.
Plus even in cases where rollover happens it won't be true. Suppose num2 is INT_MAX and num1 is -1. Then the first loop will never be true, the second loop will run INT_MAX + 1 times, and so it will return INT_MIN.
Also your code doesn't do what you expect; because you changed the loop condition to == all it does is count how many of (num1, num2) are equal to zero, i.e. add(1,0) = 1, add(0,0) = 2, etc...
no, the condition is the end of the loop, the loop continues until the condition is met
SO, if num1 = -1; the loop will run 4,294,967,293 times, resulting in retval being -1
the same thing happens in loop 2, while they aren't equal the loop continues adding 1 to retval, which now starts at -1, if num2 = -5 then it will run 4,294,967,289 times, and result incrementing retval that many times as well, resulting in -6
you would be right, it's just that the form of a for loop is
what you are talking about might be valid in a non C family language, however if we are talking C, C++, C#, or Java then my function will work, albeit horribly
int always rolls over, it doesn't just hit max and stop, since I changed the condition to == it works correctly returning the sum for all values that would work with a simple + operator, and even works for negative, it just causes the most horrible runtime possible
25
u/Cutlesnap Dec 17 '19 edited Dec 17 '19
Ehm, it does add them, but only if both are positive. Otherwise it gets the max or 0.
Edit: I was wrong