#include <stdio.h>
#include <cmath>
void update(int *a,int *b) {
*a = *a + *b;
int absDifference = *a - *b > 0 ? *a - *b : -(*a - *b);
*b = absDifference;
}
/*
void update(int *a,int *b) {
int sum = *a + *b;
int absDifference = *a - *b > 0 ? *a - *b : -(*a - *b);
*a = sum;
*b = absDifference;
} */
int main() {
int a, b;
int *pa = &a, *pb = &b;
scanf("%d %d", &a, &b);
update(pa, pb);
printf("%d\n%d", a, b);
return 0;
}
The upper function is not working on hackerrank but the commented function is working. I don't get the difference.
There is no difference between *a+=*b
and int sum = *a+*b
where sum = *a
.
But! Where you put your condition check makes a lot of difference.
In first function, the *a
is being added with *b
and then condition check is for *a - *b
which is nothing but original (or old) value of *a
.
*a = *a + *b;
int absDifference = *a - *b > 0 ? *a - *b : -(*a - *b);
In second function, *a
is unchanged. Only sum
is being updated with *a + *b
. Here the condition is checking for the original *a
minus *b
. Only after this condition check, *a
is being updated.
int sum = *a + *b;
int absDifference = *a - *b > 0 ? *a - *b : -(*a - *b);
*a = sum;
Equivalent of first function with a intermediate sum
variable, would be this:
int sum = *a + *b;
*a = sum;
int absDifference = *a - *b > 0 ? *a - *b : -(*a - *b);
And this is what not working for you.
Try to use this function.
int absDifference = *a - *b > 0 ? *a - *b : -(*a - *b);
*a = *a + *b;
*b = absDifference;
In your upper function *a = *a + *b;
*a value had changed. So int absDifference = *a - *b > 0 ? *a - *b : -(*a - *b);
int absDifference = *a - *b > 0 ? *a - *b : -(*a - *b);
this statement result not same with follow function.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.