Article directory
172. Zero after factorial
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);
}
};
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;
}
};
1342. Number of operations to change numbers to 0
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. The number of nodes in a complete binary tree
/**
* 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. Opening Ceremony Fireworks
/**
* 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();
}
};