0
\$\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.

\$\endgroup\$

migrated from stackoverflow.com Jan 10 '16 at 17:28

This question came from our site for professional and enthusiast programmers.

1
\$\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;
}
\$\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;  
}
\$\endgroup\$
  • 1
    \$\begingroup\$ Now this is inefficient! \$\endgroup\$ – Olivier Grégoire Dec 25 '15 at 11:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy