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)
 { a = 0; b =0; c =0; }
  if (b == 13)
 { b=0; c=0; }
  if (c == 13)
 { c=0; }
  return a + b + c;
}


5 comments :

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

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

    ReplyDelete
  3. Can anyone explain me as I'm unable to understand it

    ReplyDelete
  4. public int luckySum(int... nums) {
    int sum=0;
    for(int n:nums){
    if(n==13)
    return sum;
    else
    sum+=n;
    }

    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