Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

190. Reverse Bits [ Wrong Answer ] #2

Open
bilong opened this issue Mar 29, 2016 · 1 comment
Open

190. Reverse Bits [ Wrong Answer ] #2

bilong opened this issue Mar 29, 2016 · 1 comment

Comments

@bilong
Copy link

bilong commented Mar 29, 2016

I tried your code of 190 and it didn't pass.
I recommend my solution:

/**
 * @param {number} n - a positive integer
 * @return {number} - a positive integer
 */
var reverseBits = function(n) {
    var s = n.toString(2).split(""), c="";
    for (i=0; i<32; i++) {
        if ((s[s.length-1-i] == "0") || (s[s.length-1-i] == "1"))
            c = c + s[s.length-1-i];
        else
            c = c + "0";
    }
    return parseInt(c, 2);
}; 
chihungyu1116 pushed a commit that referenced this issue Feb 27, 2017
@drjkuo
Copy link

drjkuo commented Aug 12, 2017

Another version

/**
 * @param {number} n - a positive integer
 * @return {number} - a positive integer
 */
var reverseBits = function(n) {
    // reverse n
    var ans = 0;
    for (var i=0; i<32; i++) {
        ans = ans << 1 | (n&1);
        n = n >> 1;
    }
    
    // signed to unsigned
    var fans = 0;
    for (i=0; i<32; i++) {
        var tmp = (ans&1)? Math.pow(2,i) : 0;
        fans += tmp;
        ans = ans >> 1;
    }
    return (fans);
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants