数学题

172. Factorial Trailing Zeroes

Given an integer n, return the number of trailing zeroes in n!.

Note: Your solution should be in logarithmic time complexity. (Easy)

分析:求n的阶乘中末位0的个数,也就是求n!中因数5的个数(2比5多),简单思路是遍历一遍,对于每个数,以此除以5求其因数5的个数,但会超时。

考虑到一个数n比他小能被5整除的数的个数是一定的(n / 5),由此再考虑能被25整除,125整除的数的个数,得到如下算法:

代码:

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

258. Add Digits

Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.

For example:

Given num = 38, the process is like: 3 + 8 = 111 + 1 = 2. Since 2 has only one digit, return it. (Easy)

Follow up:
Could you do it without any loop/recursion in O(1) runtime?

分析:

考虑到

ab % 9 = (9a + a + b) % 9 = (a + b) % 9;

abc % 9 = (99a + 9 b + a + b + c) % 9 = (a + b + c) % 9;

所以求到其只有个位数位置即用其mod 9即可,考虑到被9整除的数应该返回9而非0,采用先减一再加一方式处理。

代码:

 class Solution {
public:
int addDigits(int num) {
if (num == ) {
return ;
}
return (num - ) % + ;
}
};

268. Missing Number

Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array.

For example,
Given nums = [0, 1, 3] return 2. (Medium)

分析:

采用先求和(前n项和),再将求和结果与数组和相减的方法,求得差哪个数

代码:

 class Solution {
public:
int missingNumber(vector<int>& nums) {
int n = nums.size();
int sum1 = n * (n + ) / ;
int sum2 = ;
for (int i = ; i < nums.size(); ++i) {
sum2 += nums[i];
}
return sum1 - sum2;
}
};
 

最新文章

  1. es6之变量的解构赋值
  2. 蒙特卡洛模拟入门的几个小例子(R语言实现)
  3. Python之实用的IP地址处理模块IPy
  4. 爬虫requests模块 1
  5. 尝试u3d中将代码与编辑器分离
  6. C#——Marshal.StructureToPtr方法简介
  7. winform连接ACCESS数据库
  8. JavaScript window
  9. .net发邮件 附件文件名乱码
  10. UTC+0800是什么意思
  11. 在asp.net mvc中使用PartialView返回部分HTML段
  12. mybatis--面向接口编程
  13. java的四舍五入算法
  14. OC基础4:类和方法
  15. Angular组件——组件生命周期(一)
  16. python类:magic魔术方法
  17. 011_TCP专项研究监控
  18. sys os
  19. 【NOIp2004提高组】食虫算 题解
  20. 【读书笔记】iOS-强类型与弱类型

热门文章

  1. [code]彩色图像直方图均衡化 histogram_rgb
  2. MySQL-Utilities:mysqldiff
  3. 用windows命令解压chm文件
  4. php数据几行代码导出到excel(非插件)
  5. 通过游戏学python 3.6 第一季 第二章 实例项目 猜数字游戏--核心代码--猜测次数 可复制直接使用 娱乐 可封装 函数
  6. 惊!VUE居然数据不能驱动视图?$set详细教程
  7. LintCode 合并两个排序
  8. mysql过多sleep连接 修改timeout配置节约连接数 配置连接数
  9. 洛谷P1966 [NOIP2013提高组Day1T2]火柴排队
  10. 【扩展推荐】Laravel-ide-helper 高效的 IDE 智能提示插件 | Laravel China 社区 - 高品质的 Laravel 和 PHP 开发者社区 - Powered by PHPH