博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
leetcode 29. Divide Two Integers
阅读量:7124 次
发布时间:2019-06-28

本文共 1672 字,大约阅读时间需要 5 分钟。

Given two integers dividend and divisor, divide two integers without using multiplication, division and mod operator.

Return the quotient after dividing dividend by divisor.

The integer division should truncate toward zero.

Example 1:

Input: dividend = 10, divisor = 3Output: 3

Example 2:

Input: dividend = 7, divisor = -3Output: -2

Note:

  • Both dividend and divisor will be 32-bit signed integers.
  • The divisor will never be 0.
  • Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231,  231 − 1]. For the purpose of this problem, assume that your function returns 231 − 1 when the division result overflows.

转载自:https://blog.csdn.net/lixq05/article/details/81157304

这个思路比较清晰

class Solution {public:long long ABS(long long a){    return a > 0 ? a : -a;}int divide(int dividend, int divisor){    if (divisor == 0 || (dividend == INT_MIN && divisor == -1))        return INT_MAX;    long long a = ABS((long long)dividend);    long long b = ABS((long long)divisor);    long long sign = ((dividend < 0) ^ (divisor < 0)) ? -1 : 1;    long long res=0;    long long tmp[33], times[33];    //第一组数据填充    tmp[0] = b;    times[0] = 1;    int index = 0;    //一直填充到临界大于a的位置    while (a >= tmp[index] && index < 33)    {        index++;        tmp[index] = tmp[index - 1] + tmp[index - 1];        times[index] = times[index - 1] + times[index - 1];    }    //遍历填充数据    for (int j = index - 1; j >= 0; j--)    {        while (a >= tmp[j])        {            res += times[j];            a -= tmp[j];        }           }    res = (sign == 1) ? res : -res;    return (int)res;}};

 

转载于:https://www.cnblogs.com/LUO77/p/10489489.html

你可能感兴趣的文章
Python3.x和Python2.x的区别
查看>>
原子变量类Atomic详解(java.util.Concurrent)
查看>>
Nginx 外的另一选择,轻量级开源 Web 服务器 Tengine 发布新版本
查看>>
常见的分布式文件系统介绍
查看>>
日期相关的格式设置
查看>>
通过Spring-boot整合dubbo框架
查看>>
C程序三子棋
查看>>
不知道SQL SERVER账户密码,生成创建用户的语句
查看>>
php 缩略图生成类,支持imagemagick及gd库两种处理
查看>>
我的友情链接
查看>>
11. 哈希表(1)
查看>>
node js 打包文件
查看>>
div的offsetLeft与style.left区别
查看>>
LAMP介绍与基本安装
查看>>
我的友情链接
查看>>
我的友情链接
查看>>
linux 查看进程占用内存
查看>>
数据库系统原理中的基本概念
查看>>
我的友情链接
查看>>
Windows sever 2008 R2 ---虚拟机安装
查看>>