• 【Leetcode】【Medium】Divide Two Integers


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

    If it is overflow, return MAX_INT.

    解题思路:

    模拟除法运算,但是不能试用 * / % 操作。

    先思考边界条件,再开始做题:

    0、除数为0无意义,需要和出题人沟通此边界是否存在(leetcode中并未考察除数为0的情况,默认除数不为0);

    1、传入被除数/除数两个int做除法,什么情况返回值overflow:被除数为-2147483648,除数为-1,结果2147483648越界,此时按题目要求,应该返回INT_MAX。

    2、在计算被除数包含多少个除数的过程中,需要不停的累加除数直到累加值超过被除数,此时累加值不可控,可能越界。因此应该使用long long 类型进行运算(32位/64位系统都适用)。

    想好以上需要注意的边界条件后,使用二分查找的思路:

    例如100 ÷ 7:

    1、可先对除数7进行左移操作,7->14->28->56->112,112大于100,停止左移,左移倍数为8;

    2、100 - 56 = 44,则继续计算44 ÷ 7,对7左移,7->14->28->56,56大于44,停止左移,左移倍数为4;

    3、44 - 28 = 16,计算16 ÷ 7,左移倍数2;

    4、16 - 14 = 2, 此时2 < 7, 左移倍数0,停止运算;

    结果为 8 + 4 + 2 = 14.

    代码编写过程中,注意被除数和除数的符号。

    代码:

     1 class Solution {
     2 public:
     3     int divide(int dividend, int divisor) {
     4         if (dividend == INT_MIN && divisor == -1)
     5             return INT_MAX;
     6         
     7         int sign = (dividend > 0 ^ divisor > 0) ? -1 : 1;
     8         long long end = abs((long long)(dividend));
     9         long long sor = abs((long long)(divisor));
    10 
    11         int ans = 0;
    12         while (end >= sor) {
    13             long long cur_sor = sor;
    14             int count = 1;
    15             while (cur_sor + cur_sor <= end) {
    16                 cur_sor <<= 1;
    17                 count <<= 1;
    18             }
    19             end -= cur_sor;
    20             ans += count;
    21         }
    22         
    23         if (sign > 0)
    24             return ans;
    25         else 
    26             return 0 - ans;
    27     }
    28 };
  • 相关阅读:
    Iscroll滑动无效
    原生js 无缝滚动组件
    原生 js dialog弹窗组件
    html5 历史管理
    html5拖拽属性
    highcharts 数据图设置X轴间隔显示效果
    highcharts柱状图含有正负柱设置不同颜色的方法
    移动端滑动插件 swiper
    千分位添加和去掉方法
    dubbo常用类和路径
  • 原文地址:https://www.cnblogs.com/huxiao-tee/p/4408777.html
Copyright © 2020-2023  润新知