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; }
LOL ADAM LIKES POOOP
ReplyDeletepublic int sumLimit(int a, int b) {
ReplyDeleteif( String.valueOf(a).length() == String.valueOf(a+b).length()){
return a+b;
} else {
return a;
}
}
public int sumLimit(int a, int b) {
ReplyDeleteint sum = a+b;
int lena=(String.valueOf(a)).length();
int len= (String.valueOf(sum)).length();
return len>lena ? a: sum;
}
String.valueOf is for strings only not int
Deletereturn String.valueOf(a+b).length() == String.valueOf(a).length() ? a+b:a;
ReplyDeletepublic int sumLimit(int a, int b) {
ReplyDeletereturn (String.valueOf(a + b).length() != String.valueOf(a).length())? a : a + b;
}
int sum = a + b;
ReplyDeleteint 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;