10. 字符串
10. 字符串
繁琐的字符串处理
public String fractionToDecimal(int numerator, int denominator) {
//handle exception
if(denominator == 0) return "NaN";
if(numerator == 0) return "0";
//build a StringBuilder
StringBuilder sb = new StringBuilder();
//check the sign
Long n = new Long(numerator);
Long d = new Long(denominator);
if(n * d < 0){
sb.append("-");
}
//make n and d all positive
n = Math.abs(n);
d = Math.abs(d);
//get the divide result
sb.append(n/d);
//if no remainder, return
if(n % d == 0){
return sb.toString();
}
sb.append(".");
long r = n % d;
Map<Long, Integer> map = new HashMap<>();//key is the remainder, value is the index of this remainder in StringBuilder
while(r > 0){
if(map.containsKey(r)){
sb.insert(map.get(r), "(");
sb.append(")");
break;
}else{
map.put(r, sb.length());//put into hashmap first
r *= 10;
sb.append(r / d);
r %= d;
}
}
return sb.toString();
}Validate IP address
Detect Capital
Last updated