Java > Logic-1 > sortaSum (CodingBat Solution)

Problem:

Given 2 ints, a and b, return their sum. However, sums in the range 10..19 inclusive, are forbidden, so in that case just return 20.

sortaSum(3, 4) → 7
sortaSum(9, 4) → 20
sortaSum(10, 11) → 21


Solution:

public int sortaSum(int a, int b) {
  int sum = a+b;
  
  if(sum >= 10 && sum <= 19)
    return 20;
  else
    return sum;
}


5 comments :

  1. public int sortaSum(int a, int b) {
    int sum = a + b;
    return sum >= 10 && sum <= 19 ? 20 : sum;
    }

    ReplyDelete
  2. public int sortaSum(int a, int b) {
    int sum = a+b;
    boolean inRange = sum >= 10 && sum <= 19;
    return !inRange ? sum:20;

    }

    ReplyDelete
  3. public int sortaSum(int a, int b) {
    return ( 10 <= (a + b) && (a + b) <= 19)? 20 : (a + b);
    }

    ReplyDelete
  4. In JavaScript:

    function sortaSum(a, b) {
    if(a + b >= 10 && a + b <= 20) {
    return 20
    } else {
    return a + b
    }
    }

    ReplyDelete
  5. public int sortaSum(int a, int b)
    {
    int sum;
    sum=a+b;
    if(sum>=10 && sum<=19)
    {
    return 20;
    }
    return sum;
    }

    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