引言

数学计算的模拟类题目,往往是要求实现某种计算(比如两数相除),实现的过程中会有所限定,比如不允许乘法等等。

这类题目首先要注意计算过程中本身的特殊情况。比如求相除,则必须首先反映过来除数不能为0。

其次要记得考虑负数的情况,如果计算范围不单单是整数,还要考虑double的比较方式。

最后要注意越界情况,这个是最容易犯错的,只能具体问题具体分析。

例题 1 不用"+ - * / "做加法

这道题来自于剑指Offer,为了归类,我把它放到了这里。

面试题 47(*),不用加减乘除做加法(位运算易想到,怎么用就是个技术活了)(附 不定义新变量前提下交换两数的方法)

例题 2 Pow(x, n)

Implement pow(xn).

class Solution {
public:
double pow(double x, int n) { }
};

这道题目我在 面试题 11,求double类型的n次幂(double数值的比较不能用==,求幂的logN复杂度方法) 中写过。

要注意的就是:

1) 0 的 0 次幂无意义。

2) 0的负数次幂无意义。

3) 所有非零数的 0次幂为1。

4) double x 判断是否为0时,不能用简单的 == 0判断,因为double类型总是存在误差。

实现,时间复杂度 log(n),"n"是函数中的参数n

class Solution {
public:
double pow(double x, int n) {
if(n == ) return ;
if(equal(x, 0.0)) return ;
return (n > ? powCore(x, n) : 1.0/powCore(x, -n));
}
private:
bool equal(double x, double y){
if((x-y) < 0.00001 && (x-y) > -0.00001) return true;
return false;
}
double powCore(double x, int n){
if(n == ) return ;
double tmp = pow(x, n/);
return tmp*tmp*(n& ? x : );
}
};

另一个不用递归直接迭代实现的版本:

class Solution {
public:
double pow(double x, int n) {
if(n == ) return ;
if(n < && (x < 0.000001 && x > -0.000001)){
if(n < ) return ( << );
}
bool pos = (n > );
unsigned int tmp = abs(n);
double res = 1.0;
while(tmp){
if(tmp&) res *= x;
tmp = tmp >> ;
x *= x;
}
return (pos ? res : (double)(1.0/res));
}
};

例题 3 Divide Two Integers

Divide two integers without using multiplication, division and mod operator.

class Solution {
public:
int divide(int dividend, int divisor) {
}
};

这道题相较于前一道稍复杂些。首先考虑divisor为0的情况,再考虑负数的情况。

接着考虑解体方法,由于乘除都不能用,只能用加法,而如果直接累加自然会超时。我的思路是定义一个长32的数组path[32],path[0] = divisor, path[i] = path[i-1] + path[i-1]。path[32]不一定全被填满,当计算出path[i] > dividend时,path[i] 就不会被记录。由于path[i] 有大于 dividend的可能,因此临时存储计算结果的数定义为long long。

然后用这个path[32] 去凑成dividend,相除结果其实就是凑得过程中 1 << i 的相加(i 是 path[] 的 index)。

第一版代码如下:

class Solution {
public:
int divide(int dividend, int divisor) {
if(divisor == ) return ;
if(dividend == ) return ; bool minus1 = false, minus2 = false, minus = false;
if(divisor < ){
divisor = ( - divisor);
minus1 = true;
}
if(dividend < ){
dividend = ( - dividend);
minus2 = true;
}
minus = (minus1 ^ minus2); //结果的正负号, minus若为true,结果就添加负号。 if(dividend < divisor) return ;
long long cache = divisor;
int* path = new int[];
int ind = ;
for(; cache <= dividend; path[ind] = (int)cache, ++ind, cache += cache); //填充path[]
cache = path[--ind]; int res = << ind; //从path的最末尾开始凑dividend
while(ind >= ){
if(cache == dividend) return minus ? (-res) : res;
if(cache > dividend){
cache -= path[ind];
res -= << ind;
}
for(--ind; ind >= && cache < dividend; cache += path[ind], res += << ind);
}
return minus ? (-res) : res;
}
};

这版代码在执行 sln.divide(-1010369383, -2147483648) 出现错误。

原因在于 开始的

dividend = (0 - dividend);

补码表示下,int下限绝对值比上限绝对值大1。dividend = -2147483648时,0-dividend 结果并非是2147483648。因此dividend 和 divisor的绝对值应该用unsigned int 表示。

考虑到这一点,当dividend = -2147483648 时,res 和 path 也有越过 int上限的可能,因此它们应该定义为 unisgned int。

改进后的代码,改动了一些参数的 格式,这次AC了。

class Solution {
public:
int divide(int dividend, int divisor) {
if(divisor == ) return ;
if(dividend == ) return ; bool minus1 = false, minus2 = false, minus = false;
unsigned int divd, divr;
if(divisor < ){
divr = ( - divisor);
minus1 = true;
}else{
divr = divisor;
}
if(dividend < ){
divd = ( - dividend);
minus2 = true;
}else{
divd = dividend;
}
minus = (minus1 ^ minus2); //结果的正负号, minus若为true,结果就添加负号。 if(divd < divr) return ;
long long cache = divr;
unsigned int* path = new unsigned int[];
int ind = ;
for(; cache <= divd; path[ind] = (unsigned int)cache, ++ind, cache += cache); //填充path[]
cache = path[--ind]; unsigned int res = << ind; //从path的最末尾开始凑dividend
while(ind >= ){
if(cache == divd) return minus ? (-res) : res;
if(cache > divd){
cache -= path[ind];
res -= << ind;
}
for(--ind; ind >= && cache < divd; cache += path[ind], res += << ind);
}
return minus ? (-res) : res;
}
};

[LeetCode] 数学计算模拟类问题:加法,除法和幂,注意越界问题。题 剑指Offer,Pow(x, n) ,Divide Two Integers的更多相关文章

  1. leetcode 338. Counting Bits,剑指offer二进制中1的个数

    leetcode是求当前所有数的二进制中1的个数,剑指offer上是求某一个数二进制中1的个数 https://www.cnblogs.com/grandyang/p/5294255.html 第三种 ...

  2. 剑指offer 65. 不用加减乘除做加法(Leetcode 371. Sum of Two Integers)

    剑指offer 65. 不用加减乘除做加法(Leetcode 371. Sum of Two Integers) https://leetcode.com/problems/sum-of-two-in ...

  3. LeetCode:“剑指 Offer”

    LeetCode:"剑指 Offer" 刷题小菜鸡,花了几天时间做了一遍 LeetCode 上给出的 "剑指 Offer" 在此做一下记录 LeetCode主页 ...

  4. 剑指offer编程题Java实现——面试题12相关题大数的加法、减法、乘法问题的实现

    用字符串或者数组表示大数是一种很简单有效的表示方式.在打印1到最大的n为数的问题上采用的是使用数组表示大数的方式.在相关题实现任意两个整数的加法.减法.乘法的实现中,采用字符串对大数进行表示,不过在具 ...

  5. [leetcode] 剑指 Offer 专题(一)

    又开了一个笔记专题的坑,未来一两周希望能把<剑指Offer>的题目刷完

  6. 【剑指Offer】不用加减乘除做加法 解题报告(Java)

    [剑指Offer]不用加减乘除做加法 解题报告(Java) 标签(空格分隔): 剑指Offer 题目地址:https://www.nowcoder.com/ta/coding-interviews 题 ...

  7. 剑指Offer——网易校招内推笔试题+模拟题知识点总结

    剑指Offer--网易校招内推笔试题+模拟题知识点总结 前言 2016.8.2 19:00网易校招内推笔试开始进行.前天晚上利用大约1小时时间完成了测评(这个必须做,关切到你能否参与面试).上午利用2 ...

  8. 【Java】 剑指offer(65) 不用加减乘除做加法

      本文参考自<剑指offer>一书,代码采用Java语言. 更多:<剑指Offer>Java实现合集   题目 写一个函数,求两个整数之和,要求在函数体内不得使用+.-.×. ...

  9. 剑指offer 66. 构建乘积数组(Leetcode 238. Product of Array Except Self)

    剑指offer 66. 构建乘积数组 题目: 给定一个数组A[0, 1, ..., n-1],请构建一个数组B[0, 1, ..., n-1],其中B中的元素B[i] = A[0] * A[1] * ...

随机推荐

  1. c# 画image

    这是一个例子,从数据库中读取然后赋伪彩,生成bitmap,给到imagebox控件(其image属性为平铺). https://pan.baidu.com/s/1hf_fGFHjGoDK_gywuhg ...

  2. 03 JAVA IO

    java.io包中定义了多个流类型来实现输入输出功能,以不同的角度进行分类: 按数据流的方向不同可以分为输入流和输出流 按处理数据单位不通可以分为字节流和字符流 按照功能不同可以分为节点流和处理流 所 ...

  3. 团队开发NABCD

    团队成员介绍: 李青:绝对的技术控,团队中扮演“猪”的角色,勤干肯干,是整个团队的主心骨,课上紧跟老师的步伐,下课谨遵老师的指令,课堂效率高,他的编程格言“没有编不出来的程序,只有解决不了的bug”. ...

  4. tensorflow之分类学习

    写在前面的话 MNIST教程是tensorflow中文社区的第一课,例程即训练一个 手写数字识别 模型:http://www.tensorfly.cn/tfdoc/tutorials/mnist_be ...

  5. HDU 5229 ZCC loves strings 博弈

    题目链接: hdu:http://acm.hdu.edu.cn/showproblem.php?pid=5229 bc:http://bestcoder.hdu.edu.cn/contests/con ...

  6. 未能加载文件或程序集“log4net, Version=1.2.10.0, Culture=neutral, PublicKeyToken=1b44e1d426115821”或它的某一个依赖项。系统找不到指定的文件。

    在网上找了很久,很多个地方让修改配置文件,也有重装log4net的. 如文章:使用Common.Logging与log4net的组件版本兼容问题 我检查下发现项目中的package包中的Log4net ...

  7. C++进阶之_类型转换

    C++进阶之_类型转换 1.类型转换名称和语法 C风格的强制类型转换(Type Cast)很简单,不管什么类型的转换统统是: TYPE b = (TYPE)a C++风格的类型转换提供了4种类型转换操 ...

  8. 【leetcode】62.63 Unique Paths

    62. Unique Paths A robot is located at the top-left corner of a m x n grid (marked 'Start' in the di ...

  9. jquery mobiscroll 滑动、滚动

    mobiscroll : 滑动选择 2.13.2版本免费,官网(mobiscroll.com)收费 先从官方下载2.13.2体验版下来,查看例子结合官方API学习( http://docs.mobis ...

  10. 第117天:Ajax实现省市区三级联动

    Ajax实现省市区三级联动 思路: (1)首先获取省份信息 (2)发起Ajax请求,注意dataType中的T大写 (3)封装回调函数,回调函数success中用$.each循环每一条数据,动态创建o ...