Saturday, July 16, 2016

Reverse unsigned 32 bit integer - facebook code lab - how to express Math.pow using bit shift

July 16, 2016

 Julia enjoyed the workout using facebook code lab. She actually learned a few things about Type conversion in bit manipulation:

  int - java - 32 bit 
  Java does not have unsigned int, use long. 
  But it causes problems! 

 She struggles and then she learns lessons. 

This blog has everything about more than 5 practices, but it is hard to know what is going on.
http://juliachencoding.blogspot.ca/2016/07/reverse-unsigned-32-bit-integer.html


 So, dedicate one blog on this issue: 

2nd practice: not working, error on 32 bit integer, left most significant bit 1 means negative number. 
https://gist.github.com/jianminchen/7bfdcd0c1643bf01c2bf6ba7acea6f70

Sorry, wrong answer. Your program's output doesn't match the expected output. You can try testing your code with custom input and try putting debug statements in your code.
Your submission failed for the following input:
A : 3
Your function returned the following :
-1073741824
The expected returned value :
3221225472
line 11:  ret += 1 << power;
1 is int with 32 bit.
http://stackoverflow.com/questions/1032982/is-a-java-int-always-32-bits

should be: ret += ((long)1) << power;

3rd practice: fail to fix the issue. 
https://gist.github.com/jianminchen/2b753978ffe983600a031a0fcda7b3a6

4th practice: Use bit manipulation - left shift to get 2^n value - code is working

https://gist.github.com/jianminchen/6a5c1ab71b01414f008b22386000ee59

No comments:

Post a Comment