Java > Logic-1 > maxMod5 (CodingBat Solution)

Problem:

Given two int values, return whichever value is larger. However if the two values have the same remainder when divided by 5, then the return the smaller value. However, in all cases, if the two values are the same, return 0. Note: the % "mod" operator computes the remainder, e.g. 7 % 5 is 2.

maxMod5(2, 3) → 3
maxMod5(6, 2) → 6
maxMod5(3, 2) → 3


Solution:

public int maxMod5(int a, int b) {
  if (a == b)
    return 0;
    
  if (a % 5 == b % 5)
    return Math.min(a,b);
  
  return Math.max(a,b);
}


6 comments :

  1. public int maxMod5(int a, int b) {
    if(a == b){
    return 0;
    }
    return (a % 5 == b % 5)? Math.min(a, b): Math.max(a, b);
    }

    ReplyDelete
  2. public int maxMod5(int a, int b) {
    return (a == b)? 0 : (a % 5 == b % 5)? Math.min(a, b): Math.max(a, b);
    }

    ReplyDelete
  3. public int maxMod5(int a, int b) {
    int larger = Integer.MIN_VALUE;
    int smaller = Integer.MAX_VALUE;
    if (a > b){
    larger = a;
    smaller = b;
    } else {
    larger = b;
    smaller = a;
    }
    if (a!=b && a % 5 == b % 5) {
    return smaller;
    }
    if (a==b) {
    return 0;
    }
    return larger;
    }

    ReplyDelete
  4. boolean equalMod=(a%5==b%5);
    if(a>b){
    if(equalMod) return b;
    return a;
    }else if(b>a){
    if(equalMod) return a;
    return b;
    }else return 0;

    ReplyDelete
  5. public int maxMod5(int a, int b) {
    if(a==b)
    return 0;
    if(a%5==b%5){
    if(a>b)
    return b;
    else return a;
    }else if(a>b){
    return a;
    }else return b;
    }

    ReplyDelete

Follow Me

If you like our content, feel free to follow me to stay updated.

Subscribe

Enter your email address:

We hate spam as much as you do.

Upload Material

Got an exam, project, tutorial video, exercise, solutions, unsolved problem, question, solution manual? We are open to any coding material. Why not upload?

Upload

Copyright © 2012 - 2014 Java Problems  --  About  --  Attribution  --  Privacy Policy  --  Terms of Use  --  Contact