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.
3 Answers 3
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;
}
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;
}
-
2\$\begingroup\$ Now this is inefficient! \$\endgroup\$Olivier Grégoire– Olivier Grégoire2015年12月25日 11:36:44 +00:00Commented Dec 25, 2015 at 11:36
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;
}