Facebook Interview Question
Software EngineersCountry: United States
public class Solution {
public String getRepetitivePattern(int dividend, int divisor) {
if(divisor == 0 || dividend % divisor = 0) {
return null; // There is no pattern
}
dividend = Math.Abs(dividend);
divisor = Math.Abs(divisor);
dividend = (dividend % divisor) * 10;
StringBuilder sb = new StringBuilder();
// Map of dividend to starting index of pattern
Map<Integer, Integer> cache = new HashMap<>();
int newDividend = dividend, quotient = 0;
// Return null in case we can never find a pattern
while(cache.size() < Integer.MAX_VALUE) {
quotient = (int)(dividend / divisor);
if(cache.contains(newDividend)) {
return sb.substring(cache.get(newDividend));
}
if (!cache.contains(newDividend)) {
cache.put(newDividend, substring.length());
substring.append(quotient);
}
newDividend = (dividend % divisor) * 10;
}
return null;
}
}
do manual division and if the remainder reapears the pattern will repeat. The code below will put the repeating sequence in "()" e.g. 1/3 = 0.(3), 4 / 3 = 1.(3), 1/6 = 0.1(6)
- Chris June 08, 2017