172. 阶乘后的零
计算阶乘
直接计算n的阶乘。这样算需要考虑的一个主要问题就是一定会有溢出。我们处理的方式就是先看他末尾有没有0,有0先去掉0并且答案数加一,然后给阶乘的结果只保留后几位,这样既不影响后面的计算,又不会溢出。
class Solution {
public:
int trailingZeroes(int n) {
int ans=0,res=1;
for(int i=1;i<=n;i++) {
res*=i;
while(res%10==0&&res!=1) res/=10,ans++;
res%=100000;
}
return ans;
}
};
寻找因子5
最后得到的结果末尾有0,也就是有10这个因子。再分解一下质因子就可以发现是含有2和5两个因子且他们中数量小的一个就是10的数量。然后再观察一步就能发现2这个因子的数量一定是远多于5这个因子的,所以问题就转化成了找5的数量。
class Solution {
public:
int trailingZeroes(int n) {
int ans=0;
for(int i=1;i<=n;i++) {
int j=i;
while(j%5==0) {
ans++;
j/=5;
}
}
return ans;
}
};
递归版本寻找因子5
class Solution {
public:
int trailingZeroes(int n) {
if(n==0) return 0;
int sum=0,m=n;
while(m%5==0) m/=5,sum++;
return sum+trailingZeroes(n-1);
}
};
1342. 将数字变成 0 的操作次数
模拟
依据题意进行模拟
class Solution {
public:
int numberOfSteps(int num) {
int ans=0;
while(num) {
if(num%2) num--;
else num/=2;
ans++;
}
return ans;
}
};
递归版本
class Solution {
public:
int numberOfSteps(int num) {
if(num==0) return 0;
if(num%2) return 1+numberOfSteps(num-1);
return 1+numberOfSteps(num/2);
}
};
222. 完全二叉树的节点个数
递归
节点数就等于根节点加上左儿子的子节点数加上右儿子的子节点数
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int countNodes(TreeNode* root) {
if(root==nullptr) return 0;
return countNodes(root->left)+countNodes(root->right)+1;
}
};
LCP 44. 开幕式焰火
dfs
题目大意就是给你一棵树,让你寻找其中的不同值。找不同我们都会,就是一个哈希表存出现次数就可以了嘛。因为这道题的数值是以树的形式给出的,所以我们加一个树的遍历,在这里直接深搜
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
unordered_map<int,int>mp;
void dfs(TreeNode *root) {
if(root==NULL) return;
mp[root->val]++;
dfs(root->left),dfs(root->right);
}
int numColor(TreeNode* root) {
mp.clear();
dfs(root);
return mp.size();
}
};