読者です 読者をやめる 読者になる 読者になる

SRM158 div2 MEDIUM

The base of a number system is the number of different values each digit can represent. For example, in base-2 (binary), there are 2 values each digit can take: 0 and 1. In base-10, a digit can take values 0 through 9, inclusive. Sometimes, it is difficult to determine which base a numerical expression is in. An equation is valid for a given base if all of the digits are less than the base, and the numerical meaning of the equation is correct. For example, "1+1=10" for base-10 satisfies the rule that the digits are all less than 10, but 1+1 = 2 in base-10, so the equation is not correct for base-10.
If we assume that the characters '0'-'9' represent the values 0 - 9, and the characters 'A'-'J' represent the values 10 - 19, then we can represent numbers with a base up to 20. The equation will be in the following form:+=
Where each is a String consisting of characters '0'-'9' and 'A'-'J', which does not have any extra leading zeros, and is at most 5 digits long.
Given an equation as defined above, you should return which bases in the range of 2 to 20, inclusive, are valid for the equation. Return the bases in a int[] in ascending order.

  1 import java.util.regex.*;
  2 import java.util.*;
  3
  4 public class BaseMystery {
  5     boolean valid(String[] parts, int n) {
  6         try{
  7             return Integer.valueOf(parts[2], n) == Integer.valueOf(parts[0], n) + Int    eger.valueOf(parts[1], n);
  8         } catch(Exception e) {
  9             return false;
 10         }
 11     }
 12
 13     int[] toIntegerList(List<Integer> list) {
 14         int[] ret = new int[list.size()];
 15         for(int i=0;i<list.size();i++) {
 16             ret[i] = list.get(i);
 17         }
 18         return ret;
 19     }
 20 ----
 21     public int[] getBase(String equation) {
 22         String[] parts = equation.split("[=+]");
 23         List<Integer> ret = new ArrayList<Integer>();
 24
 25         for(int n=2; n<=20; n++) {
 26             if(valid(parts, n))
 27                 ret.add(n);
 28         }
 29                                                                                       exist.");
 30         return toIntegerList(ret);
 31     }
 32


System.arraycopy(ret, 0, list, 0, list.size())つかったらいい。

© karahiyo