Facebook | Phone | Count uniform numbers in range

Had a phone screen interview (5 mins intro, then 35 mins coding) and the question was to count uniform numbers given in range i.e. 222 is uniform whereas 223 is not.

Sample test cases:
Input: x = 75 and y = 300
Output: expected value = 5
Since 77, 88, 99, 111 and 222 are uniform in range

The question fumbled me a bit but came up with a hacky solution that works for digits that are greater than size 1

public int countUniformNumbers(long x, long y) {
	int ans = 0;
	long start = x;
	while (start <= y) {
	  String s = String.valueOf(start);
	  int n = s.length() - 1;
	  char temp = s.charAt(0);
	  int i = 1;
	  while (i <= n) {
		if (s.charAt(i) != temp)
		  break;
		if (i == n)
		  ans++;
		i++;
	  }
	  start++;
	}
	return ans;
}

Moving onto onsite but thought I would share since this is a bit tricky yet simple

Comments (37)