0
Help! Why is the result "J" here?
char agentName(char partner) { return ~(partner * -1); } int main() { printf("%c", agentName('K')); }
12 Answers
+ 7
According to your code
partner * -1 means:
75 * -1 = -75
-75 in binary = 11111111 10110101
Taking bitwise complement of -75
~11111111 10110101 = 00000000 01001010
Now 00000000 01001010 = 74 in ascii
Which is J's ascii value
+ 4
mesarthim
All letters and characters we see as text have a numeric association which computers /codes use to process information.
This goes right down to binary level, -> another discussion.
K -1 = J
+ 2
Ascii code of k is 107
107 - 1 =106
Ascci code of j is 106
+ 2
Thanks Rushikesh
+ 2
Thanks HK Lite
+ 2
Thanks Rik Wittkopp
+ 1
Because of ascii
%c print ascii values
+ 1
Remove the dirt of code
like this
return partner -1;
+ 1
mesarthim
Save & run this code to see what I mean.
PS: it is python, but the base principal is the same.
https://code.sololearn.com/cR8q6PcSDb0A/?ref=app
+ 1
When you negate an integer as (k * -1) [or more simply (-k)] the result is the same as ((~k)+1). FYI, this operation is described as "taking the two's complement of k."
Observe:
If ~k + 1 = -k
Then ~k = -k - 1
Substituting -partner for k, watch what happens when we reduce ~(-partner).
~(-partner) = -(-partner) - 1
= partner - 1
So agentName() simply returns (partner -1).
If partner = 'K', then agentName() returns the next lower letter, which is 'J'.
+ 1
Thanks Brian
0
HK Lite
Wow, my head hurts!
Great answer
đđ