问题描述如下:
“在附件name.txt中有5000个人名,首先将其按照字母排序,然后计算出每个人名的价值,然后用价值与排序后列表的位置相乘,得到人名的得分。
例如:排序之后,“COLIN”的价值为3+15+12+9+14=53,在排序后的位置是938位,所以其得分为938*53=49714.
所有名字得分的总和是多少?”
代码实现如下:
/**
* 初始化name.txt,并将人名进行排序
* @return
*/
private static String[] init() {
String[] s = null;
try {
BufferedReader br = new BufferedReader(new FileReader(new File(
"name.txt")));
s = br.readLine().replace("\"", "").split(",");
Arrays.sort(s);
} catch (Exception e) {
// TODO: handle exception
}
return s;
}
/**
* 计算得分总和
* @return
*/
private static int getScoreSum() {
int scoreSum = 0;
String[] s = init();
for (int i = 0; i < s.length; i++) {
int worth = 0;
for (int j = 0; j < s[i].length(); j++) {
worth += (s[i].charAt(j) - 'A' + 1);//每个字母的价值
}
scoreSum += (i + 1)*worth;//
}
return scoreSum;
}
可以得到答案871198282。
请不吝赐教。
@anthor ClumsyBirdZ