我用java刷 leetcode 剑指 Offer 64. 求1+2+…+n
Posted 深林无鹿
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了我用java刷 leetcode 剑指 Offer 64. 求1+2+…+n相关的知识,希望对你有一定的参考价值。
这里有leetcode题集分类整理!!!
我的憨憨AC:
class Solution {
public int sumNums(int n) {
int time = n / 2;
int ztime = n % 2;
int res = (1+n) * time + ztime * ((n + 1) / 2);
return res;
}
}
官方:
改造递归为 && 逻辑短路
class Solution {
public int sumNums(int n) {
boolean flag = n > 0 && (n += sumNums(n - 1)) > 0;
return n;
}
}
作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/qiu-12n-lcof/solution/qiu-12n-by-leetcode-solution/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
快速乘:
class Solution {
public int sumNums(int n) {
int ans = 0, A = n, B = n + 1;
boolean flag;
flag = ((B & 1) > 0) && (ans += A) > 0;
A <<= 1;
B >>= 1;
flag = ((B & 1) > 0) && (ans += A) > 0;
A <<= 1;
B >>= 1;
flag = ((B & 1) > 0) && (ans += A) > 0;
A <<= 1;
B >>= 1;
flag = ((B & 1) > 0) && (ans += A) > 0;
A <<= 1;
B >>= 1;
flag = ((B & 1) > 0) && (ans += A) > 0;
A <<= 1;
B >>= 1;
flag = ((B & 1) > 0) && (ans += A) > 0;
A <<= 1;
B >>= 1;
flag = ((B & 1) > 0) && (ans += A) > 0;
A <<= 1;
B >>= 1;
flag = ((B & 1) > 0) && (ans += A) > 0;
A <<= 1;
B >>= 1;
flag = ((B & 1) > 0) && (ans += A) > 0;
A <<= 1;
B >>= 1;
flag = ((B & 1) > 0) && (ans += A) > 0;
A <<= 1;
B >>= 1;
flag = ((B & 1) > 0) && (ans += A) > 0;
A <<= 1;
B >>= 1;
flag = ((B & 1) > 0) && (ans += A) > 0;
A <<= 1;
B >>= 1;
flag = ((B & 1) > 0) && (ans += A) > 0;
A <<= 1;
B >>= 1;
flag = ((B & 1) > 0) && (ans += A) > 0;
A <<= 1;
B >>= 1;
return ans >> 1;
}
}
作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/qiu-12n-lcof/solution/qiu-12n-by-leetcode-solution/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
数学 + 快速乘
class Solution {
public int sumNums(int n) {
return quickMul(n, n + 1) >> 1;
}
int quickMul(int a, int b){
int res = 0;
boolean flag;
flag = b != 0 &&
(flag = (b & 1) == 1 && (res += a + quickMul(a<<=1, b>>=1)) > 0 ||
(res += quickMul(a<<=1, b>>=1)) > 0);
return res;
}
}
以上是关于我用java刷 leetcode 剑指 Offer 64. 求1+2+…+n的主要内容,如果未能解决你的问题,请参考以下文章
Mac系统解决Vscode中LeetCode插件不能刷剑指offer题库