LeetCode之“數學”:Reverse Integer && Reverse Bits

來源:互聯網
上載者:User

標籤:

  1. Reverse Integer

  題目連結

  題目要求:

  Reverse digits of an integer.

  Example1: x = 123, return 321
  Example2: x = -123, return -321

  click to show spoilers.

  Have you thought about this?

  Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!

  If the integer‘s last digit is 0, what should the output be? ie, cases such as 10, 100.

  Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?

  For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

  這道題主要要注意末尾為0和越界的問題。程式如下:

 1 class Solution { 2 public: 3     int reverse(int x) { 4         if(x == INT_MIN) 5             return 0; 6              7         int num = abs(x); 8         int last = 0; 9         long result = 0; 10         while(num != 0)11         {12             last = num % 10;13             result = result * 10 + last;14             num /= 10;15         }16         17         if(result > INT_MAX)18             return 0;19         20         return (x > 0) ? result : -result;21     }22 };
  2. Reverse Bits

  題目連結

  題目要求:

  Reverse bits of a given 32 bits unsigned integer.

  For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represented in binary as00111001011110000010100101000000).

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

  Related problem: Reverse Integer

  Credits:
  Special thanks to @ts for adding this problem and creating all test cases.

  下邊的程式中用到了bitset資料結構,需要注意的是,bits[0]才是最地位。

 1 class Solution { 2 public: 3     uint32_t reverseBits(uint32_t n) { 4         uint32_t one = 1; 5         bitset<32> bits; 6         int i = 31; 7         while(n != 0 && i > -1) 8         { 9             bits[i] = n & one;10             n = n >> 1;11             i--;12         }13         14         return bits.to_ulong();15     }16 };

 

LeetCode之“數學”:Reverse Integer && Reverse Bits

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.