Java > Logic-1 > sumLimit (CodingBat Solution)

Problem:

Given 2 non-negative ints, a and b, return their sum, so long as the sum has the same number of digits as a. If the sum has more digits than a, just return a without b. (Note: one way to compute the number of digits of a non-negative int n is to convert it to a string with String.valueOf(n) and then check the length of the string.)

sumLimit(2, 3) → 5
sumLimit(8, 3) → 8
sumLimit(8, 1) → 9


Solution:

public int sumLimit(int a, int b) {
  String aString = String.valueOf(a);
  int aLen = aString.length();
  String sumString = String.valueOf(a+b);
  int sumLen = sumString.length();
  
  if (sumLen == aLen)
    return a + b;
  else
    return a;
  
}


7 comments :

  1. LOL ADAM LIKES POOOP

    ReplyDelete
  2. public int sumLimit(int a, int b) {

    if( String.valueOf(a).length() == String.valueOf(a+b).length()){
    return a+b;
    } else {
    return a;
    }
    }

    ReplyDelete
  3. public int sumLimit(int a, int b) {
    int sum = a+b;
    int lena=(String.valueOf(a)).length();
    int len= (String.valueOf(sum)).length();
    return len>lena ? a: sum;
    }

    ReplyDelete
    Replies
    1. String.valueOf is for strings only not int

      Delete
  4. return String.valueOf(a+b).length() == String.valueOf(a).length() ? a+b:a;

    ReplyDelete
  5. public int sumLimit(int a, int b) {
    return (String.valueOf(a + b).length() != String.valueOf(a).length())? a : a + b;
    }

    ReplyDelete
  6. int sum = a + b;
    int countA = 1;
    int countS = 1;
    int result = 0;
    for (int i = 1; i < 100; i++) {

    if (a /(Math.pow(10,i)) >= 1)
    countA++;
    if (sum /(Math.pow(10,i)) >= 1)
    countS++;
    }
    if (countA == countS)
    result = sum;
    else if (countA < countS)
    result = a;
    return result;

    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