前言
hello 大家好啊,九日集训的最后一天了,短暂的胜利了哈哈哈。
完结撒花❀❀❀哈哈哈
🐱🐱🐱
172. 阶乘后的零
class Solution {
public:
int trailingZeroes(int n) {
//只有2*5末尾才有0,只看2,5及其倍数就行
//10!= 2*(2*2)*5*(2*3)*(2*2*2)(2*5) 2个2*5 故末尾2个0
//其实只需要数以下,因子里有几个5就行
int count = 0;
while(n >= 5)
{
count += n / 5;
n /= 5;
}
return count;
}
};
1342. 将数字变成 0 的操作次数
循环计数
class Solution {
public:
int numberOfSteps(int num) {
int count = 0;
while(num)
{
++count;
if(num % 2 == 0)
num /= 2;
else
num -= 1;
}
return count;
}
};
递归
class Solution {
public:
int numberOfSteps(int num) {
if(num == 0)
return 0;
if(num % 2 == 0)
return numberOfSteps(num/2) + 1;
else
return numberOfSteps(num-1) + 1;
}
};
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. 开幕式焰火
/**
* 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:
int Hash[1010] = {0};
//哈希思想
void traverse(TreeNode* root)
{
if(root)
{
Hash[root->val] = 1;
traverse(root->left);
traverse(root->right);
}
}
int numColor(TreeNode* root)
{
int sum = 0;
//遍历二叉树
traverse(root);
for(int i = 0; i < 1010; ++i)
{
if(Hash[i] == 1)
++sum;
}
return sum;
}
};
397. 整数替换
递归
class Solution {
public:
int integerReplacement(int n) {
if (n == 1) {
return 0;
}
if (n % 2 == 0) {
return 1 + integerReplacement(n / 2);
}
return 2 + min(integerReplacement(n / 2), integerReplacement(n / 2 + 1));
}
};
转换类型的递归
class Solution {
public:
long func(long n)
{
if(n == 1)
return 0;
if(n % 2 == 0)
return 1 + func(n / 2);
else
return 1 + min(func(n+1), func(n-1));
}
int integerReplacement(int n) {
//递归
//由于2^31 + 1 会溢出,因此想办法转换为long
return (int)func((long)n);
}
};
尾声
🌹🌹🌹
写文不易,如果有帮助烦请点个赞~ 👍👍👍
Thanks♪(・ω・)ノ🌹🌹🌹
😘😘😘
👀👀由于笔者水平有限,在今后的博文中难免会出现错误之处,本人非常希望您如果发现错误,恳请留言批评斧正,希望和大家一起学习,一起进步ヽ( ̄ω ̄( ̄ω ̄〃)ゝ,期待您的留言评论。
附GitHub仓库链接
附联系方式(2076188013)(QQ)