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 str = Integer.toString(a+b);
String str2 = Integer.toString(a);

if(str.length() == str2.length())
return a+b;
else 
return a;
  
}


5 comments :

  1. boolean isEqual = String.valueOf(a).length() == String.valueOf(a+b).length();
    return isEqual ? a + b : a;

    ReplyDelete
  2. if (String.valueOf(a+b).length() == String.valueOf(a).length())
    return a + b;
    return a;

    ReplyDelete
  3. public static int sumLimit2(int a, int b) {
    String str = Integer.toString(a + b);
    String str2 = Integer.toString(a);
    if (str.length() == str2.length()) {
    return a + b;
    }
    return a;
    }

    ReplyDelete
  4. public int sumLimit(int a, int b) {
    int sum = a + b;
    if ( no_of_digits(sum) > no_of_digits(a) ) return a;
    return sum;
    }

    public int no_of_digits(int number) {
    return String.valueOf(number).length();
    }

    ReplyDelete
  5. return (String.valueOf(a+b).length() == String.valueOf(a).length()) ? a+b:a;
    It's simple, but one liners (when possible) will always be more pleasant to read through.

    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