Leetcode-190 Reverse Bits

Source: Internet
Author: User

Problem Description:

Reverse bits of a given the unsigned integer.

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

Followup:
If This function is called many times, what would you optimize it?

Related problem: Reverse Integer

C + + code implementation:

<span style= "Font-size:12px;color: #000000;" >class Solution {public:    uint32_t reversebits (uint32_t N) {                uint32_t result = 0;//Represents the result of the computed int temp = 0;       The count is judged whether it has been moved 32 times, because most of the numbers on the left side of N are 0, so it is not necessary to loop 24-bit while (n! = 0) {result = (Result << 1) | (N & 1);//The result of each previous loop calculation is shifted one bit to the left, plus the number of digits taken from N (n & 1) n >>= 1;    + + temp;} if (Temp < +) {result <<= (32-temp);} return result;}            ; </span>


Java implementation: Failed to run on the system, I do not know how to handle the problem of unsigned int

public class Reverse_bits {//need treat N as an unsigned valuepublic long reversebits (long N) {Long result = 0;//represents the meter calculated result int temp = 0;//int Int_size = integer.size;//int type size while ((n! = 0) && (temp<=int_size)) {result = (Resul T << 1) | (N & 1); n >>= 1;++temp;} if (Temp < int_size) {result <<= (int_size-temp);} return result;} public static void Main (string[] args) {reverse_bits reverse_bits = new Reverse_bits (); System.out.println (Reverse_bits.reversebits (2147483648L));}}

The numbers written directly in the Java code are of type int, meaning that the number ranges from -2^31 to 2^31-1, regardless of the type assigned to the number.

When the direct assignment argument is 2147483648, the literal ... of type int is an out of range error, add L to the array, or use Long.phraselong () to resolve the problem





Leetcode-190 Reverse Bits

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.