题目一:
链接:累加
解题思路:
1、可以使用循环进行累加求和;
2、可以用python中的list求和
C++:
class Solution {
public:
int sumNums(int n) {
return ((1+n)*n)/2;
}
};
Python:
class Solution(object):
def sumNums(self, n):
"""
:type n: int
:rtype: int
"""
s=[ i for i in range(1,n+1)]
return sum(s)
JAVA:
class Solution {
public int sumNums(int n) {
int s=0;
for(int i=1;i<=n;i++){
s+=i;
}
returns; }
}
题目二:
链接:2的幂
解题思路:
枚举2的幂有2,4,8…2^31
C++:
class Solution {
public:
bool isPowerOfTwo(int n) {
if(n<=0)
return false;
if(n==1)
return true;
unsigned int k=2;
for(int i=1;i<=31;i++){
if(k==n){
return true;
break;
}
k*=2;
}
return false;
}
};
题目三:
题目链接:3的幂
解题思路:
枚举3的幂有1,3,9,27…3^20
python:
class Solution(object):
def isPowerOfThree(self, n):
"""
:type n: int
:rtype: bool
"""
if n==1:
return True
if n<=0:
return False
k=3
for i in range(20):
if k==n:
return True
k*=3
return False
题目四:
链接:4的幂
解题思路:
枚举4的幂有1,4,16…2^15
Java
class Solution {
public boolean isPowerOfFour(int n) {
if(n==1)
return true;
if(n<=0)
return false;
int k=4;
for(int i=1;i<=15;i++){
if(k==n){
return true;
}
k*=4;
}
return false;
}
}
题目五:
链接:第k个因子数
解题思路:
暴力循环破解
c++:
class Solution {
public:
int kthFactor(int n, int k) {
int x=0;
for(int i=1;i<=n;i++){
if(n%i==0){
x++;
if(k==x){
return i;
}
}
}
return -1;
}
};
题目六:
链接:有效的完全平方数
解题思路:
C++
class Solution {
public:
bool isPerfectSquare(int num) {
for(int i=1;i<=num/2+2;i++){
if((long long)i*i==num)
return true;
}
return false;
}
};