1.统计能整除数字的位数
Solution
class Solution {
public:
int countDigits(int num) {
int ans = 0;
int n = num;
while(n){
int t = n % 10;
if(num % t == 0){
ans++;
}
n /= 10;
}
return ans;
}
};
2.数组乘积中的不同质因数数目
Solution
class Solution {
public:
int distinctPrimeFactors(vector<int>& nums) {
unordered_set<int> ans;
for(auto x : nums){
//对每一个元素求其质因数
int i = 2;
while(i*i <= x){
if(x % i == 0){
ans.insert(i);
x /= i;
while(x % i == 0){
x /= i;
}
}
i++;
}
if(x > 1){
ans.insert(x);
}
}
return ans.size();
}
};
3.将字符串分割成值不超过 K 的子字符串
Solution
class Solution {
public:
int minimumPartition(string s, int k) {
long long ans = 1, sum = 0;
for(auto x : s){
int t = x - '0';
if(t > k) return -1;
sum = sum * 10 + t;
if(sum > k){
ans++;
sum = t;
}
}
return ans;
}
};
4.范围内最接近的两个质数
Solution
用到了素数筛,筛出素数暴力跑就行。
class Solution {
public:
vector<int> closestPrimes(int left, int right) {
vector<int> prime;
vector<int> book(right+5,0);
book[0] = book[1] = 1;
//质数筛
for(int i=2;i<=right;i++) {
if(!book[i]) {
prime.push_back(i);
}
for(int j=0;j<prime.size() && prime[j]*i <= right;j++) {
book[prime[j] * i] = 1;
}
}
int nums = INT_MAX;
int len = prime.size();
vector<int> ans = {-1,-1};
for(int i = 0;i < len-1;i++){
if(prime[i] < left) continue;
if(nums > prime[i+1] - prime[i]){
ans = {prime[i], prime[i+1]};
nums = prime[i+1] - prime[i];
}
}
return ans;
}
};
标签:prime,周赛,return,int,sum,Solution,326,ans
From: https://www.cnblogs.com/TTS-TTS/p/17019041.html