Java > Logic-2 > luckySum (CodingBat Solution)

Problem:

Given 3 int values, a b c, return their sum. However, if one of the values is 13 then it does not count towards the sum and values to its right do not count. So for example, if b is 13, then both b and c do not count.

luckySum(1, 2, 3) → 6
luckySum(1, 2, 13) → 3
luckySum(1, 13, 3) → 1


Solution:

public int luckySum(int a, int b, int c) {
  if (a == 13)
    return 0;
  else if (b == 13)
    return a;
  else if (c == 13)
    return a + b;
  else
    return a + b +c;
}


8 comments :

  1. public int luckySum(int a, int b, int c) {
    int sum = 0;
    if (a != 13) sum += a;
    else return sum;
    if (b != 13) sum += b;
    else return sum;
    if (c != 13) sum += c;
    return sum;
    }

    ReplyDelete
  2. int sum = 0;
    if (a != 13 && b !=13 && c != 13) {return sum = sum + a+b+c;}
    else if (a==13 && b!=13 && c!=13){return sum = sum; }
    else if (b == 13 && c != 13 && a!=13) {return sum = sum +a;}
    else if (c==13 && a!=13 && b!=13) {return sum = sum +a+b;}
    else if (b==13 && b==c) {return sum = sum +a;}
    else {return sum;}

    ReplyDelete
  3. public int luckySum(int a, int b, int c) {

    int[] arr = {a,b,c};
    int sum = 0;

    for (int i = 0; i< arr.length; i++){
    if(arr[i] == 13){
    break;
    }
    sum += arr[i];

    }
    return sum;
    }

    ReplyDelete
  4. public int loneSum(int a, int b, int c) {

    if (a == b && a == c && b == a){
    return 0;
    } else if(b == c){
    return a;
    } else if(a == c){
    return b;
    } else if(a == b) {
    return c;
    } else {
    return a + b + c;
    }
    }

    ReplyDelete
  5. public int luckySum(int a, int b, int c) {
    if( a != 13 && b != 13 && c != 13){
    return a + b + c;
    } else if( a == 13){
    return 0;
    } else if (b == 13){
    return a;
    } else if (c == 13){
    return a + b;
    } else {
    return 0;
    }
    }

    ReplyDelete
  6. return (a==13)?0:(b==13)?a:(c==13)?a+b:a+b+c;

    ReplyDelete
  7. private final int luckySum(int a, int b, int c) {
    if (a == 13){
    return 0;
    }
    if (b == 13){
    return a;
    }
    if (c == 13){
    return a + b;
    }
    return a + b + c;
    }

    ReplyDelete
  8. public int luckySum(int a, int b, int c)
    {
    int sum = 0;
    if (a != 13)
    {
    sum = a + b;
    if(b == 13)
    {
    sum -= b;
    }

    if(b != 13 && c!= 13)
    {
    sum += c;
    }
    }
    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