How can m1 = m2, if m1= min(c, d) and m2 = min(a, b)? obviously they are not equal to each other... I'm very lost.
public static int min(int a, int b, int c, int d) {
//write your code here
int m1 = 0;
int m2 = min(a, b);
if (c < d)
m1 = c;
else
m1 = d;
if (m2 < m1)
m1 = m2;
return m1;
}
public static int min(int a, int b) {
//write your code here
int m;
if (a < b)
m = a;
else
m = b;
return m;
}
Can someone please explain why this worked?
Under discussion
Comments (7)
- Popular
- New
- Old
You must be signed in to leave a comment
Bupal Junior
22 May 2019, 16:36
public class Solution {
public static int min(int a, int b, int c, int d) {
int n, m, x;
n = min(a,b);
m = min(c,d);
x = min(n,m);
return x;
}
public static int min(int a, int b) {
int small;
if ( a < b) {
small = a;
} else {
small = b;
}
return small;
}
public static void main(String[] args) throws Exception {
System.out.println(min(-20, -10));
System.out.println(min(-20, -10, -30, -40));
System.out.println(min(-20, -10, -30, 40));
System.out.println(min(-40, -10, -30, 40));
}
}
-2
Guadalupe Gagnon
22 May 2019, 16:33
What Thomas said. The single equals (=) sign is the assignment operator and does not check equality. Anything on the left side will be assigned to the value on the right side. To check for equality you would need the double equals sign (==), which will return true if the objects are equal, or false otherwise.
m1 = min(c,d) and m2 = min(a,b), you correctly read those 2 expressions; m1 = m2 uses the same exact operator and works exactly like the 2 prior ones.
0
suraj tiwari
22 May 2019, 15:56
u can also try this!!
public class Solution {
public static int min(int a, int b, int c, int d) {
//write your code here
if(a
0
ThomasLC
22 May 2019, 04:18useful
It doesn't mean equal. It means to set m1 to m2's value because m2 is now effectively the smallest number as the condition before that was [if m2 < m1]
It's an extra step for no reason though. Can just put return m2 if m2 is smaller and return m1 if m1 is smaller
+1
romeo
23 May 2019, 13:02
like this?
if (m2 < m1) {
return m2;
}
else {
return m1;
}
0
ThomasLC
24 May 2019, 03:21
That's right, you're getting it! :)
0
romeo
24 May 2019, 11:54
Thanks, I just tried it and found out that if I were to use that method, I would first have to make a variable: int m1 = (c, d);
Much easier than it looks at first :)
0