Hey folks,
Given an integer x, write a function that multiplies x with 3.5 and returns the integer result. You are not allowed to use %, /, *.
Examples : Input: 2 Output: 7 Input: 5 Output: 17 (Ignore the digits after decimal point)
Solution:
1. We can get x3.5 by adding 2x, x and x/2. To calculate 2x, left shift x by 1 and to calculate x/2, right shift x by 2. The function should not use any of the arithmetic operators (+, ++, –, -, … etc). Sum of two bits can be obtained by performing XOR (^) of the two bits. Carry bit can be obtained by performing AND (&) of two bits. We can extend this logic for integers. If x and y don’t have set bits at same position(s), then bitwise XOR (^) of x and y gives the sum of x and y. To incorporate common set bits also, bitwise AND (&) is used. Bitwise AND of x and y gives all carry bits. We calculate (x & y) << 1 and add it to x ^ y to get the required result. The idea is to use subtractor logic. Write a program to subtract one from a given number. The idea is to use bitwise operators. Like addition, Write a function Add() that returns sum of two integers. The function should not use any of the arithmetic operators (+, ++, –, -, … etc). Sum of two bits can be obtained by performing XOR (^) of the two bits. Carry bit can be obtained by performing AND (&) of two bits. We can extend this logic for integers. If x and y don’t have set bits at same position(s), then bitwise XOR (^) of x and y gives the sum of x and y. To incorporate common set bits also, bitwise AND (&) is used. Bitwise AND of x and y gives all carry bits. We calculate (x & y) << 1 and add it to x ^ y to get the required result. The idea is to use subtractor logic. The use of operators like ‘+’, ‘-‘, ‘’, ‘/’, ‘++’, ‘–‘ …etc. are not allowed.
Another way of doing this could be by doing a binary multiplication by 7 then divide by 2 using only <<, ^, &, and >>.
But here we have to mention that only positive numbers can be passed to this method.
Below is the implementation of the above approach:
// Java program for above approach
import
java.io.*;
class
GFG
{
// Function to multiple number
// with 3.5
static
int
multiplyWith3Point5(
int
x)
{
int
r =
0
;
// The 3.5 is 7/2, so multiply
// by 7 (x * 7) then
// divide the result by 2
// (result/2) x * 7 -> 7 is
// 0111 so by doing mutiply
// by 7 it means we do 2
// shifting for the number
// but since we doing
// multiply we need to take
// care of carry one.
int
x1Shift = x <<
1
;
int
x2Shifts = x <<
2
;
r = (x ^ x1Shift) ^ x2Shifts;
int
c = (x & x1Shift) | (x & x2Shifts)
| (x1Shift & x2Shifts);
while
(c >
0
) {
c <<=
1
;
int
t = r;
r ^= c;
c &= t;
}
// Then divide by 2
// r / 2
r = r >>
1
;
return
r;
}
// Driver Code
public
static
void
main(String[] args)
{
System.out.println(multiplyWith3Point5(
5
));
}
}
Output
17