solution.json 2.8 KB
Newer Older
每日一练社区's avatar
每日一练社区 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
{
  "type": "code_options",
  "author": "https://github.com/begeekmyfriend/leetcode",
  "source": "solution.md",
  "exercise_id": "7d7aea05317f4fa29074594e49a0cccc",
  "keywords": "位运算,数学",
  "title": "两数相除",
  "desc": [
    {
      "content": "\n<p>给定两个整数,被除数&nbsp;<code>dividend</code>&nbsp;和除数&nbsp;<code>divisor</code>。将两数相除,要求不使用乘法、除法和 mod 运算符。</p><p>返回被除数&nbsp;<code>dividend</code>&nbsp;除以除数&nbsp;<code>divisor</code>&nbsp;得到的商。</p><p>整数除法的结果应当截去(<code>truncate</code>)其小数部分,例如:<code>truncate(8.345) = 8</code> 以及 <code>truncate(-2.7335) = -2</code></p><p>&nbsp;</p><p><strong>示例&nbsp;1:</strong></p><pre><strong>输入:</strong> dividend = 10, divisor = 3<strong><br />输出:</strong> 3<strong><br />解释: </strong>10/3 = truncate(3.33333..) = truncate(3) = 3</pre><p><strong>示例&nbsp;2:</strong></p><pre><strong>输入:</strong> dividend = 7, divisor = -3<strong><br />输出:</strong> -2<strong><br />解释:</strong> 7/-3 = truncate(-2.33333..) = -2</pre><p>&nbsp;</p><p><strong>提示:</strong></p><ul>\t<li>被除数和除数均为 32 位有符号整数。</li>\t<li>除数不为&nbsp;0。</li>\t<li>假设我们的环境只能存储 32 位有符号整数,其数值范围是 [&minus;2<sup>31</sup>,&nbsp; 2<sup>31&nbsp;</sup>&minus; 1]。本题中,如果除法结果溢出,则返回 2<sup>31&nbsp;</sup>&minus; 1。</li></ul>",
      "language": "markdown"
    }
  ],
  "answer": [
    {
      "content": "",
      "language": "cpp"
    }
  ],
  "prepared": [
    [
      {
        "content": "",
        "language": "cpp"
      }
    ],
    [
      {
        "content": "",
        "language": "cpp"
      }
    ],
    [
      {
        "content": "",
        "language": "cpp"
      }
    ]
  ],
  "template": {
    "content": "#include <bits/stdc++.h>\nusing namespace std;\nclass Solution\n{\npublic:\n\tint divide(int dividend, int divisor)\n\t{\n\t\tint signal = 1;\n\t\tunsigned int dvd = dividend;\n\t\tif (dividend < 0)\n\t\t{\n\t\t\tsignal *= -1;\n\t\t\tdvd = ~dvd + 1;\n\t\t}\n\t\tunsigned int dvs = divisor;\n\t\tif (divisor < 0)\n\t\t{\n\t\t\tsignal *= -1;\n\t\t\tdvs = ~dvs + 1;\n\t\t}\n\t\tint shift = 0;\n\t\twhile (dvd > dvs << shift)\n\t\t{\n\t\t\tshift++;\n\t\t}\n\t\tunsigned int res = 0;\n\t\twhile (dvd >= dvs)\n\t\t{\n\t\t\twhile (dvd < dvs << shift)\n\t\t\t{\n\t\t\t\tshift--;\n\t\t\t}\n\t\t\tres |= (unsigned int)1 << shift;\n\t\t\tdvd -= dvs << shift;\n\t\t}\n\t\tif (signal == 1 && res >= INT_MAX)\n\t\t{\n\t\t\treturn INT_MAX;\n\t\t}\n\t\telse\n\t\t{\n\t\t\treturn res * signal;\n\t\t}\n\t}\n};",
    "language": "cpp"
  },
  "node_id": "dailycode-a6beddb2efc64ddc8a28e593dfefc807",
  "license": "csdn.net",
  "created_at": 1637894158,
  "topic_link": "https://bbs.csdn.net/topics/600470833"
}