Skip to content

Instantly share code, notes, and snippets.

@bchetty
Last active December 17, 2015 16:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bchetty/5638702 to your computer and use it in GitHub Desktop.
Save bchetty/5638702 to your computer and use it in GitHub Desktop.
GCJ 2012 - Recycled Numbers
import java.util.HashSet;
/**
*
* @author Babji Prashanth, Chetty
*/
public class RecycledNumbers {
public int findNumberOfPairs(int A, int B) {
int res = 0;
int len = ("" + A).length();
int count = len-1;
char c2 = ("" + B).charAt(0);
System.out.println("A : " + A + " B : " + B);
for(int i=A;i<=B;i++) {
HashSet<Integer> partnerSet = new HashSet<Integer>();
String input = "" + i;
char c1 = input.charAt(0);
for(int j=0;j<count;j++) {
String prefix = input.substring(count-j);
char c = prefix.charAt(0);
if(c < c1 || c > c2) {
continue;
}
int partner = Integer.parseInt(prefix + input.substring(0, count-j));
if(!partnerSet.contains(partner) && partner > i && partner <= B && ("" + partner).length() == len) {
//System.out.println("Partner Found : " + partner);
res++;
partnerSet.add(partner);
}
}
}
System.out.println("Num of pairs : " + res);
return res;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment