Ali Pardhan
Ali Pardhan

Reputation: 332

multiplying number in binary by two

I am trying to multiply a binary number by 2, without coveting to other counting system.

my algorithm is:

Method to hunt down 0:

private static int hunt(char[] arry, int i) {

    for (int j = i; j > 0; j--) {
        if (arry[j] == '0')
            return j;
    }
    return -1;
}

Method that flips bits from 1 to 0:

private static boolean isOneThenChange(char[] a, int i) {
    if (a[i] == '1') {
        a[i] = '0';
        return true;
    }
    return false;
}

}

I have been unsuccessful in debugging my code, i suspect it to be in step 3,4,5

How do i debug my algorithm, and get it to function as intended?

Upvotes: 0

Views: 635

Answers (1)

user5063151
user5063151

Reputation:

In binary, if you shift left, you are multiplying by 2. So, in terms of strings, if you append a 0, you are effectively multiplying by 2.

x = 1110   // 14 in decimal

x << 1     // 28 in decimal

But, since you are using strings:

String x = "1110"; // 14 in decimal

// As long as x != 0, append "0"
if (!x.equals("0")) {

  x = x + "0"; // 11100 = 28
}         

It's the same as shifting left on a base-10 number multiplies by 10:

12
120
1,200

For any base (radix) one shift to the left multiplies your number by the base. (in this case base 2). And shifting to the right effectively divides the number by the base the number and rounds down.

Upvotes: 4

Related Questions