The Java Learning Project

I started learning Java programming and found a perfect website for practicing: Codingbat.com. CodingBat is a free site of live coding problems to build coding skill in Java and Python. CodingBat is a project by Nick Parlante, a computer science lecturer at Stanford.

I will upload my solutions here.

Given two ints, each in the range 10..99, return true if there is a digit that appears in both numbers, such as the 2 in 12 and 23. (Note: division, e.g. n/10, gives the left digit while the % "mod" n%10 gives the right digit.)

shareDigit(12, 23) → true
shareDigit(12, 43) → false
shareDigit(12, 44) → false

1
2
3
4
5
6
7
public boolean shareDigit(int a, int b) {
  int a1=a/10;
  int a2=a%10;
  int b1=b/10;
  int b2=b%10;
  return (a1==b1 || a1==b2 || b1==a2 || a2==b2);
}

Given a string, return a string where for every char in the original, there are two chars.

doubleChar("The") → "TThhee"
doubleChar("AAbb") → "AAAAbbbb"
doubleChar("Hi-There") → "HHii--TThheerree"

1
2
3
4
5
6
7
8
9
public String doubleChar(String str) {
  String character="";
  String result="";
  for (int i=0; i<str.length(); i++){
    character=str.substring(i,i+1);
    result=result+character+character;
  }
  return result;
}

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

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
public int sumLimit(int a, int b) {
  int a_length=(String.valueOf(a)).length();
  int b_length=(String.valueOf(b)).length();
  int sum=a+b;
  if ((String.valueOf(sum)).length()==(String.valueOf(a)).length()) {
    return sum;
  } else {
    return a;
  }
}

Keresés

Ajánló