AC算法每日打卡-9日集训第9天-阶乘后的零等6题

172. 阶乘后的零

class Solution {
 public:
   int trailingZeroes(int n) {
       int ans=0;
       while(n>0){
           n/=5;
           ans+=n;
       }
       return ans;
        } 
       };

 1342. 将数字变成 0 的操作次数

class Solution {
public:
    int numberOfSteps (int num) {
        int cnt = 0 ;
        while(num)
        {
            if(num % 2 == 0)
                num /= 2 ;
            else 
                num--;
            cnt++ ;
        }
        return cnt ;
    }
};

 222. 完全二叉树的节点个数

class Solution {
public:
    int countNodes(TreeNode* root) {
        if (root == nullptr) return 0;
        TreeNode* left = root->left;
        TreeNode* right = root->right;
        int leftHeight = 0, rightHeight = 0; // 这里初始为0是有目的的,为了下面求指数方便
        while (left) {  // 求左子树深度
            left = left->left;
            leftHeight++;
        }
        while (right) { // 求右子树深度
            right = right->right;
            rightHeight++;
        }
        if (leftHeight == rightHeight) {
            return (2 << leftHeight) - 1; // 注意(2<<1) 相当于2^2,所以leftHeight初始为0
        }
        return countNodes(root->left) + countNodes(root->right) + 1;
    }
};

 LCP 44. 开幕式焰火

 

class Solution {
public:
    int numColor(struct TreeNode *root) {
        int ans = 0;
        
        bool flag[1001] = {false};
        dfs(root, flag);
        for (bool f : flag) {
            if (f) {
                ans++;
            }
        }
        
        return ans;
    }

    void dfs(struct TreeNode *root, bool *flag) {
        if (root != nullptr) {
            flag[root->val] = true;
            dfs(root->left, flag);
            dfs(root->right, flag);
        }
    }
};

 剑指 Offer 13. 机器人的运动范围

class Solution {
public:
 int count = 0;
 int movingCount(int m, int n, int k) {
  if (k == 0) return 1;
  vector> visited(m, vector(n));
  dfs(visited, 0, 0, m, n, k);
  return count;
 }
 void dfs(vector>& visited, int x, int y, int& m, int& n, int k)
 {
  if (x >= m || x < 0 || y >= n || y<0 || (x / 10 + x % 10 + y / 10 + y % 10)>k || visited[x][y] == 1) 
   return;
  ++count;
  visited[x][y] = 1;
  int dx[4] = { -1, 0, 1, 0 }, dy[4] = { 0, 1, 0, -1 };
  for (int q = 0; q<4; ++q){
   int i = x + dx[q], j = y + dy[q];
   dfs(visited, i, j, m, n, k);
  }
 }
};

 剑指 Offer 14- I. 剪绳子

class Solution {
public:
    int cuttingRope(int n) {
        if(n <= 3) 
        return n - 1;
        int a = n / 3, b = n % 3;
        if(b == 0) 
        return pow(3, a);
        if(b == 1) 
        return pow(3, a - 1) * 4;
        else
        return pow(3, a) * 2;
    }
};

你可能感兴趣的:(C++刷力扣题,leetcode)