class Solution {
public int countPrimes(int n) {
boolean []ispri=new boolean[n];
Arrays.fill(ispri,true);
for(int i=2;i<n;i++){
if(ispri[i]){
for(int j=2*i;j<n;j+=i){
ispri[j]=false;
}
}
}
int cnt=0;
for(int i=2;i<n;i++){
if(ispri[i])
cnt++;
}
return cnt;
}
}
class Solution {
public String convertToBase7(int num) {
return Integer.toString(num,7);
}
}
java,进制可以推广到n
class Solution {
public String convertToBase7(int num) {
StringBuilder sb=new StringBuilder();
if(num==0) return "0";
boolean flag=num<0?true:false;
num=Math.abs(num);
while(num!=0){
sb.append(num%7);
num/=7;
}
if(flag)
sb.append("-");
return sb.reverse().toString();
}
}
26jingzhi
class Solution {
public String convertToTitle(int n) {
if(n<0) return "";
StringBuilder sb=new StringBuilder();
while(n>0){
n--;
sb.append((char)(n%26+'A'));
n/=26;
}
return sb.reverse().toString();
}
}
class Solution {
public int trailingZeroes(int n) {
int cnt=0;
while(n>=5){
cnt+=n/5;
n/=5;
}
return cnt;
}
}
解题思路:中位数
class Solution {
public int minMoves2(int[] nums) {
Arrays.sort(nums);
int i=0,j=nums.length-1,cnt=0;
while(i<j){
cnt+=nums[j]-nums[i];
j--;
i++;
}
return cnt;
}
}
class Solution {
public int majorityElement(int[] nums) {
HashMap<Integer,Integer>mp=new HashMap<>();
for(int num:nums){
if(mp.containsKey(num)){
mp.put(num,mp.get(num)+1);
}
else
mp.put(num,1);
}
for(int key:mp.keySet()){
if(mp.get(key)>nums.length/2)
return key;
}
return -1;
}
}
解题思路:利用 1+3+5+7+9+…+(2n-1)=n^2,即完全平方数肯定是前n个连续奇数的和
class Solution {
public boolean isPerfectSquare(int num) {
int i=1;
while(num>0){
num-=i;
i+=2;
}
return num==0;
}
}
class Solution {
public boolean isPowerOfThree(int n) {
if(n==0) return false;
if(n==1) return true;
while(n%3==0){
n/=3;
if(n==1)
return true;
}
return false;
}
}