I need to fix these answers please help thanks. Part 2 The rules for completing
ID: 3692032 • Letter: I
Question
I need to fix these answers please help thanks. Part 2
The rules for completing lab include:
All of these problems can be done with the eight operators:
! ~ & ^ | + << >>
and some require you to stick with just a subset of these.
You are also limited to constants with length at most 8-bits
i.e. you are limited to constants with two hexadecimal digits.
You must use straight-line code – no loops or conditionals.
Each puzzle also has a rating of 1 (easiest) to 4 (hardest).
There is a limit on the number of operations you may use (just to eliminate brute force solutions).
Each puzzle is worth 5 points
The Assignment
__________________________________________________________________________________________________________________________________________________
Puzzle Seven – isPositive - Return 1 if x>0, return 0 otherwise
Difficulty Rating - 3
Legal Operators: ! ~ & ^ | + << >>
Max Ops: 12
isPositive(int x) { }
int isPositive(int x)
{
int y;
y= 1<<31;
y= x&y;
y= y| !x;
return y; ---------------look at x=-1
y=x&y =>0x80000000 (1 in left most but)
y=y|0 =>0x80000000
}
Puzzle Eight – isLess - if x < y then return 1, else return 0
Example: isLess(4,5) = 1.
Legal ops: ! ~ & ^ | + << >>
Max ops: 30
Rating: 3
isLess(int x, int y) { }
int isLess(int x, int y)
{
return ((((x+((~y)+1))>>31)+1);----check if negative, Note: wrong about overflow
}
Puzzle Nine – threeFourths - multiplies by 3/4 rounding toward 0,
Should exactly duplicate effect of C expression (x*3/4), including overflow behavior.
Examples: ezThreeFourths(11) = 8
ezThreeFourths(-9) = -6
ezThreeFourths(1073741824) = -268435456 (overflow)
Legal ops: ! ~ & ^ | + << >>
Max ops: 12
Rating: 3
int threeFourths(int x) {
int z=(x+(x<<1))>>2;-----need to add bias for negative #'s
int b1=x>>31
int b2 =z>>3
if(b1^b2)printf("overflow")---crossout the word overflow it seems
else print("not overflow")
}
}
Explanation / Answer
I have done fixes to your functions
1)
int isPositive(int x)
{
return !((x & 0x80000000) >> 31 | !x);
}
The above function will return 1 if number is positive else it will return 0
2)
int isLess(int x, int y)
{
return ((((y+((~x)+1))>>31)+1));
}
working code:
#include <iostream>
using namespace std;
int isLess(int x, int y)
{
return ((((y+((~x)+1))>>31)+1));
}
int main() {
cout<<isLess(4,5);
return 0;
}
3)
we can do this in a much simpler way:
int threeFourths(int x) {
x=(x>>1)+((x+1)>>2);
}