BigDecimal.setScale(int newScale, RoundingMode roundingMod)
方法用于格式化小数点。
翻译:scale——范围;round——范围。roundingMod取值:
BigDecimal bg = new BigDecimal(f);
double f1 = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
DecimalFormat df = new DecimalFormat("#.00");
System.out.println(df.format(f));-
// 额外用法:将格式嵌入文本
System.out.println(newDecimalFormat("光速大小为每秒,###米。").format(c));
printf
格式化输出,其中可以指定的语言环境。float result = String.format("%.2f", f);
NumberFormat nf = NumberFormat.getNumberInstance(); // 得到默认的数字格式化显示
nf.setMaximumFractionDigits(2); // integer整数,fraction分数
System.out.println(nf.format(f));
System.out.println((float)(Math.round(f*100)/100)); //如果要求精确4位就*10000然后/10000
StringBuilder sb = new StringBuilder(String.valueOf(m));
System.out.println(m.indexOf("."));
sb.setLength(10 + m.indexOf(".") + 1); // 保留十位小数
System.out.println(sb.toString());
思路:
整数部分除2逆向取余
小数部分乘2正向取整
注意:
对于大数据问题,如果暴力求解必定超时,不妨先写出一些(不)符合的数,尝试寻找规律。
判断一个数能否写出2个以上连续的数的和,观察后发现(不符合的有0,1,2,4,8 …),只有N为2的幂次方时,不能写成连续整数和的形式。
而2的幂次方二进制表示为10…0的形式,故x & (x - 1)
即可。
利用开方来减少时间,用两个数组分别来存因子,因为小于开方的因子一定对应一个大于开方的因子。
for (int i = 1; i <= Math.sqrt(n); i++) {
if (n % i == 0) {
smallToBig.add(i);
if (n / i != i) { // 去重, 当开方后的数相等时,只收集一个
bigTosmall.add(n / i);
}
}
}
对于固定数量的大小写转换,可以利用replace()来特殊处理,不必用if挨个判断。
// 要求:将日记中所有的元音字母大写,其他的小写
String result = scanner.nextLine().toLowerCase().replace('a', 'A').replace('e', 'E').replace('i', 'I').replace('o', 'O').replace('u', 'U');
思考:
/**
* 实现StringBuilder的replaceAll
*
* @param stb
* @param oldStr 被替换的字符串
* @param newStr 替换oldStr
* @return
*/
public static StringBuilder replaceAll(StringBuilder stb, String oldStr, String newStr) {
if (stb == null || oldStr == null || newStr == null || stb.length() == 0 || oldStr.length() == 0) {
return stb;
}
int index = stb.indexOf(oldStr);
if (index > -1 && !oldStr.equals(newStr)) {
int lastIndex = 0;
while (index > -1) {
stb.replace(index, index + oldStr.length(), newStr);
lastIndex = index + newStr.length();
index = stb.indexOf(oldStr, lastIndex); // indexOf(String str, int fromIndex)用于查找后续匹配的子串
}
}
return stb;
}
重写Collections工具类的Compare()方法,如果要对Map进行排序,则需将其实体类存入List中,通过getValue()/getKey()来获取相应的值。
// 以国家、金银铜三种奖牌数为输入,得到奖牌排名
Map<String, int[]> input = new HashMap<>();
List<Map.Entry<String, int[]>> output = new ArrayList<>(input.entrySet());
Collections.sort(output, (o1, o2) -> { // 升序o1大于o2返回-1,逆序则返回1
// 第一次判断
if (o1.getValue()[0] > o2.getValue()[0]) {
return -1;
} else if (o1.getValue()[0] < o2.getValue()[0]) {
return 1;
} else {
// 第二次判断
if (o1.getValue()[1] > o2.getValue()[1]) {
return -1;
} else if (o1.getValue()[1] < o2.getValue()[1]) {
return 1;
} else {
// 第三次判断
if (o1.getValue()[2] > o2.getValue()[2]) {
return -1;
} else if (o1.getValue()[2] < o2.getValue()[2]) {
return 1;
} else {
// 第四次判断
return o1.getKey().compareTo(o2.getKey());
}
}
}
});
Iterator iterator = output.iterator();
while (iterator.hasNext()) {
System.out.println(((Map.Entry<String, int[]>) iterator.next()).getKey());
}
BigDecimal的构造函数 public BigDecimal(double val) 损失了double 参数的精度。
String(scanner.next())
为参数的构造函数:public BigDecimal(String val) 来替代。
// 转换时出现精度损失的情况
float = 1.2
1.1999999999999999555910790149937383830547332763671875
1.2000000476837158203125
1E+2
的科学计数法输出。
System.out.println( new BigDecimal("100.000").stripTrailingZeros().toPlainString());
// 输出:100
三种toString()方法:
要注意nextLine()收集\n
和space
的情况。
避免:
// Method 1
if (input.nextLine() != "\n") {}
// Method 2
sc.nextLine();