>>> num = 0
>>> for i in range(100):
... if i % 2 == 0:
... num = num - i
... else:
... num = num + i
...
>>> num
50
In addition, since it is the first number minus the last number, the sum between the two values is -1, and 99/2=49.5. Therefore, there are 49 pairs in total, and the result is -49, and then combined with 99 Adding together we get 99-49=50
After a cursory look, the previous answers all used forloops. Personally, I think you should use them less if you can, and try to reduce the time to O1. Suppose the parameter is n, which is the largest number, and both are greater than 0, here it is 99
n
result
1
1
2
-1
3
1
4
-2
5
3
6
-3
When n is an odd number, the result is positive, result = ((n - 1) / 2) * (-1) + n When n is an even number, the result is negative, that is, result = (n / 2) * (-1) So, the answer is out. .
def compute(n):
if n % 2 is 1:
return int(((n - 1) / 2) * (-1) + n)
else:
return int((n / 2) * (-1))
can be calculated like this:
In addition, since it is the first number minus the last number, the sum between the two values is -1, and 99/2=49.5. Therefore, there are 49 pairs in total, and the result is -49, and then combined with 99 Adding together we get 99-49=50
After a cursory look, the previous answers all used
for
loops. Personally, I think you should use them less if you can, and try to reduce the time to O1.Suppose the parameter is n, which is the largest number, and both are greater than 0, here it is 99
When n is an odd number, the result is positive, result = ((n - 1) / 2) * (-1) + n
When n is an even number, the result is negative, that is, result = (n / 2) * (-1)
So, the answer is out. .
Code
Results