Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bit Manipulation in Python and Java

I am working on a problem wherein, the given array is as follows:

" Given a non-empty array of integers, every element appears three times except for one, which appears exactly once. Find that single one. "

For example:

Input: [2,2,3,2]
Output: 3

I am trying to solve it using Bit Manipulation, and my code in Python is as follows:

def singleNumber(self, nums):

    ans = 0
    for i in range(31):
        summ = 0
        for num in nums:
            dig = (num>>i)&1
            if dig:
                summ += 1
        summ = summ%3
        if summ:
            ans = ans | summ<<i

    return ans

All I am trying to do is, get the last bit of each number in the array and count the number of ones that I get and then %3 to get the exact 1 bits that remain and shift it to make the correct answer.

This fails test cases which have negative inputs, something like:

[-2,-2,1,1,-3,1,-3,-3,-4,-2]
O/P: 2147483644
Expected O/P: -4

However, when I do the exact same thing in Java, it works! The code is as below:

class Solution {
public int singleNumber(int[] nums) {

    int ans = 0;
    int dig = 0;

    for(int i = 0; i <=31; i++){
        int sum = 0;
        for(int num: nums){

            dig = (num>>i)&1;
            if(dig!=0){
                sum = sum + 1;    
            }
            sum = sum%3;
        }
        if(sum!= 0){
            ans = ans | sum<<i;
        }

    }
    return(ans);
   }
}

How are the bits represented in Python that is causing this difference? Can someone please tell me the difference in bit manipulations in both the languages, Python and Java?

like image 724
crazyy_photonn Avatar asked Nov 22 '25 00:11

crazyy_photonn


1 Answers

java has 32-Bit fixed int size. But in python there is no explicitly defined limit for numbers. read at (Maximum value for long integer)

A hacky solution for your problem (may not work all cases) is

return ans - 2**(32-1)
like image 129
REDDY PRASAD Avatar answered Nov 24 '25 13:11

REDDY PRASAD



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!