Java > Logic-1 > shareDigit (CodingBat Solution)

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


Solution:

public boolean shareDigit(int a, int b) {
  int aL = a / 10;
  int aR = a % 10;
  int bL = b / 10;
  int bR = b % 10;
  
  if (aL == bL || aL == bR || aR == bL || aR == bR)
    return true;
  else
    return false;
}

4 comments:

  1. int p,q,r=b;
    while(a!=0)
    {
    p=a%10;
    while(b!=0)
    {
    q=b%10;
    if(p==q)
    return true;
    b=b/10;
    }
    a=a/10;
    b=r;
    }
    return false;

    ReplyDelete
  2. public boolean shareDigit(int a, int b) {
    return a/10==b/10||
    a/10==b%10||
    a%10==b%10||
    a%10==b/10;
    }

    ReplyDelete
  3. public boolean shareDigit(int a, int b) {
    return (a /10 == b /10 || a / 10 == b % 10) || (a %10 == b /10 || a % 10 == b % 10);
    }

    ReplyDelete
  4. public boolean shareDigit(int a, int b) {
    if(a/10==b/10||a/10==b%10)
    {
    return true;
    }
    else if((a%10==b%10||a%10==b/10))
    {
    return true;
    }
    return false;

    }

    ReplyDelete