2
\$\begingroup\$

I have solved a CodingBat problem: 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

My working code is:

public boolean shareDigit(int a, int b) {
 boolean answer = false;
 int lefta = a/10;
 int righta = a % 10;
 int leftb = b/10;
 int rightb = b % 10;
 if(lefta == leftb || lefta == rightb || righta == leftb || righta == rightb){
 answer = true; 
 }
 return answer;
}

It feels extremely inefficient, and I was wondering if anyone could improve it.

200_success
145k22 gold badges190 silver badges478 bronze badges
asked Dec 25, 2015 at 9:19
\$\endgroup\$
0

3 Answers 3

2
\$\begingroup\$

You can simplify the boolean parts of your method.

public boolean shareDigit(int a, int b) {
 int lefta = a / 10;
 int righta = a % 10;
 int leftb = b / 10;
 int rightb = b % 10;
 return lefta == leftb || lefta == rightb || righta == leftb
 || righta == rightb;
}
answered Jan 10, 2016 at 19:21
\$\endgroup\$
0
\$\begingroup\$

I think your code is efficient. You just do 4 comparisons. You cannot find answer with less. Maybe instead you can use:

if( (a/10)== (b/10)|| (a/10 )==( b % 10)|| (a % 10)== (b/10) || (a % 10) == (b % 10)){
 answer = true; 
}
answered Dec 25, 2015 at 9:27
\$\endgroup\$
1
  • 2
    \$\begingroup\$ Now this is inefficient! \$\endgroup\$ Commented Dec 25, 2015 at 11:36
0
\$\begingroup\$

Usually when I see these types of questions that treat digits as tokens(is that the right word?) they typically specify not to use string manipulation. But it makes this problem much easier.

It's a bit harder to determine the Big O comparison since it uses external libraries. But we cut down the integer a to only it's unique digits (could also be done for b but in a two digit number doesn't save you much), and do only one comparison of each number so sort of O(n) vs matching each digit with every other digit O(n^2)

//Javascript, it was taking me too long to figure out Java
//But you get the gist, this also has the added benefit of
//Supporting any length number, and mismatched number lengths
// a = 12
// b = 23
function shareDigit (a, b){
 // setA = <'1', '2'>
 const setA = new Set(a.toString().split(''));
 // arrayB = ['2', '3']
 const arrayB = b.toString().split('');
 for(let i = 0; i < arrayB.length; i++) {
 if(setA.has(arrayB[i])){
 return true;
 }
 }
 return false;
}
answered Apr 11, 2020 at 14:19
\$\endgroup\$