选择题
很多Linux相关和SQL相关,有些忘了.jpg
第一题 折扣
去网上买东西,双十一打七折,双十二打八折,要是有优惠券(1/有 0没有)就再减50,问价格(输出保留两位小数)
输入:四个数,代表价格、月、日、有无优惠券(日月只可能是1111或1212)
输出:保留两位小数
思路:
- 无脑暴力,但是输出要注意小数怎么保留
double res = money(price, month, day, ifSale);
DecimalFormat df = new DecimalFormat("0.00");
- 在*0.7的时候会丢失精度,用BigDecimal维持精度
BigDecimal count1 = new BigDecimal("0.7");
res = res1.multiply(count1).doubleValue();
程序 :
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
double price = in.nextDouble();
int month = in.nextInt();
int day = in.nextInt();
int ifSale = in.nextInt();
double res = money(price, month, day, ifSale);
DecimalFormat df = new DecimalFormat("0.00");
System.out.println(df.format(res));
}
public static double money(double price, int month, int day, int ifSale) {
double res = price;
BigDecimal res1 = new BigDecimal(Double.toString(res));
if(month == 11 && day == 11) {
BigDecimal count1 = new BigDecimal("0.7");
res = res1.multiply(count1).doubleValue();
if(ifSale == 1) res = (res - 50 >= 0) ? res - 50 : 0;
}
if(month == 12 && day == 12) {
BigDecimal count2 = new BigDecimal("0.8");
res = res1.multiply(count2).doubleValue();
// res = (long) (res * 0.8f);
if(ifSale == 1) res = (res - 50 >= 0) ? res - 50 : 0;
}
return res;
}
}
第二题 兑换零钱
力扣原题:零钱兑换
思路:动态规划
/**
dp[j]: 凑足j所需要最少的硬币数
dp[j] = min(dp[j-coins[i]]+1, dp[j])
初始化:首先凑足总金额为0所需钱币的个数一定是0,那么dp[0] = 0;
考虑到递推公式的特性,dp[j]必须初始化为一个最大的数,否则就会在min(dp[j - coins[i]] + 1, dp[j])比较的过程中被初始值覆盖。
*/
class Solution {
public int coinChange(int[] coins, int amount) {
int[] dp = new int[amount + 1];
dp[0] = 0;
for(int i = 1; i < dp.length; i++){
dp[i] = Integer.MAX_VALUE;
}
for(int i = 0; i < coins.length; i++){
for(int j = coins[i]; j <= amount; j++){
if(dp[j - coins[i]] < Integer.MAX_VALUE){
dp[j] = Math.min(dp[j], dp[j - coins[i]] + 1);
}
}
}
return dp[amount] == Integer.MAX_VALUE ? -1 : dp[amount];
}
}