维护一个栈和一个计数器index。逐个数遍历,令remainder = index % 4, remainder == 0,乘以当前N值,remainder == 1,除以当前N值, remainder == 2,加当前N值, remainder == 3,减当前N值。注意Python3里面的 '//'操作是floor除法(比如 -3//2 == -2),而通常大家需要的是向0除法(-3/2== -1)。需要转成正数除,再加上负号。或者转成浮点除法,再强转为正数。C++完全没有这个问题,不用特殊处理。
class Solution {
public:
int clumsy(int N) {
stack<int> stk;
stk.push(N);
N--;
int index = 0;
while (N != 0) {
if (index % 4 == 0) {
stk.top() *= N;
} else if (index % 4 == 1) {
stk.top() /= N;
} else if (index % 4 == 2) {
stk.push(N);
} else if (index % 4 == 3) {
stk.push(-N);
}
N--;
index++;
}
int sum = 0;
while (!stk.empty()) {
sum += stk.top();
stk.pop();
}
return sum;
}
};
class Solution(object):
def clumsy(self, N):
stk = [N]
N -= 1
index = 0
while (N != 0) :
if (index % 4 == 0) :
stk.append(stk.pop() * N)
if (index % 4 == 1) :
# silly python syntax, x // y is floor division not zero direction division
# -3 // 2 == -2 !! Not -1
# stk.append((int)(stk.pop() / float(N)))
top = stk.pop()
stk.append(top // N if top > 0 else -(-top / N))
elif (index % 4 == 2) :
stk.append(N)
elif (index % 4 == 3) :
stk.append(-N)
N -= 1
index += 1
# sum = 0
# while (len(stk) > 0) :
# sum += stk.pop()
# return sum
return sum(stk)