Instructions
https://www.codewars.com/kata/resistor-color-codes/train/java
Solution:
import java.util.HashMap;
import java.util.Map;
public class DecodeResistorColors {
private static Map<String,String> map = new HashMap<String, String>();
static {
map.put("black", "0");
map.put("brown", "1");
map.put("red", "2");
map.put("orange", "3");
map.put("yellow", "4");
map.put("green", "5");
map.put("blue", "6");
map.put("violet", "7");
map.put("gray", "8");
map.put("white", "9");
map.put("gold", "5%");
map.put("silver", "10%");
}
private static String third(String power){
int count = Integer.valueOf(power);
StringBuilder sb = new StringBuilder();
for(int i = 0; i < count; i++){
sb.append("0");
}
return sb.toString();
}
public static String decodeResistorColors(String bands){
String[] arr = bands.split(" ");
String temp = map.get(arr[0]) + map.get(arr[1]) + third(map.get(arr[2]));
Float num = Float.valueOf(temp);
String suffix = "";
if(num >= 1000 && num < 1000000){
num = num / 1000;
suffix = "k";
}else if(num >= 1000000){
num = num / 1000000;
suffix = "M";
}
StringBuilder sb = new StringBuilder();
String str = String.valueOf(num);
str = str.replaceAll("\\.0", "");
sb.append(str);
sb.append(suffix);
sb.append(" ohms, ");
if(arr.length == 4){
sb.append(map.get(arr[3]));
}else{
sb.append("20%");
}
return sb.toString();
}
}
Sample Tests:
https://www.codewars.com/kata/resistor-color-codes/train/java