iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 20
0
自我挑戰組

[LeetCode with JavaScript] 一起來刷 LeetCode吧 ~~~ (ノ>ω<)ノ系列 第 20

[LeetCode with JavaScript] Day 20: Reverse Bits

觀前提醒:

  1. 我預設大家已經先思考並分析過題目,沒啥想法才開始 google 找解題靈感。若無,建議每題先花 1~2 顆番茄鐘的時間來分析題目比較好。可參考番茄鐘工作法
  2. 承上,既然已經有思考過了,那我這邊直接 po 題目 + 解題想法 + code +心得 。若已經在 code 內有足夠的註解了,那我可能解題想法 & 心得的部分就不會寫太多,免得干擾你的思考。
  3. 所有解法都是已經取得系統的 Accepted,但或許不是最優解法,請多包涵。
  4. 若對於解法不太懂,可以嘗試用 Chrome 的 debugger 來試跑看看 (教學文)
  5. 最後,歡迎在下面留言指教~教學相長才會進步歐~/images/emoticon/emoticon41.gif

題目

Reverse bits of a given 32 bits unsigned integer.

Example 1:

Input: 00000010100101000001111010011100
Output: 00111001011110000010100101000000
Explanation: The input binary string 00000010100101000001111010011100 represents the unsigned integer 43261596, so return 964176192 which its binary representation is 00111001011110000010100101000000.

Example 2:

Input: 11111111111111111111111111111101
Output: 10111111111111111111111111111111
Explanation: The input binary string 11111111111111111111111111111101 represents the unsigned integer 4294967293, so return 3221225471 which its binary representation is 10111111111111111111111111111111.

Note:

  • Note that in some languages such as Java, there is no unsigned integer type. In this case, both input and output will be given as signed integer type and should not affect your implementation, as the internal binary representation of the integer is the same whether it is signed or unsigned.
  • In Java, the compiler represents the signed integers using 2's complement notation. Therefore, in Example 2 above the input represents the signed integer -3 and the output represents the signed integer-1073741825.

Follow up:

If this function is called many times, how would you optimize it?

Constraints:

  • The input must be a binary string of length = 32

解題想法

利用 JS 本身內建函式的特性,來幫忙直接解題

  1. .toString( )把 32 bits unsigned integer 給存起來。
  2. 再用 .padStart( )把前步驟失去的0,給補回來。
  3. .split( ) + .reverse( )組合拳,把字串轉成陣列後直接翻轉過來。
  4. 最後用 .parseInt(string, 2) 轉換成整數回傳,以方便跟測資做比較。

CODE


/**
 * @param {number} n - a positive integer
 * @return {number} - a positive integer
 */
var reverseBits = function (n) {
  let arrOfN = n.toString(2).padStart(32, "0").split("").reverse();
  let result = parseInt(arrOfN.join(""), 2);
  return result;
};

心得

上述為調用內部函式的解法~
但其實還有 Bitwise operattion 的操作方式,也歡迎大家換個方式,來解這題~
/images/emoticon/emoticon58.gif


謝謝大家的收看,LeetCode 小學堂我們下次見~/images/emoticon/emoticon29.gif


上一篇
[LeetCode with JavaScript] Day 19: Number of 1 Bits
下一篇
[LeetCode with JavaScript] Day 21: Count Primes
系列文
[LeetCode with JavaScript] 一起來刷 LeetCode吧 ~~~ (ノ>ω<)ノ30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言