试题 G: 最少砝码
问题描述】
你有一架天平。现在你要设计一套砝码,使得利用这些砝码可以称出任意小于等于 N 的正整数重量。
那么这套砝码最少需要包含多少个砝码?
注意砝码可以放在天平两边。
【输入格式】
输入包含一个正整数 N。
【输出格式】
输出一个整数代表答案。
【样例输入】
7
【样例输出】
3
【样例说明】
3 个砝码重量是 1、4、6,可以称出 1 至 7 的所有重量。
1 = 1;
2 = 6 − 4 (天平一边放 6,另一边放 4);
3 = 4 − 1;
4 = 4;
5 = 6 − 1;
6 = 6;
7 = 1 + 6;
少于 3 个砝码不可能称出 1 至 7 的所有重量。
题目分析:
- 找规律 || 动态规划
- 找规律我们可以发现
需要的砝码数count=count+1
砝码的重量weight=weight*3
能够称重的重量 total=total+weight
题目代码:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
sc.close();
int weight = 1;
int count = 1;
int total = 1;
while (total < n) {
count++;
weight *= 3;
total += weight;
}
System.out.println(count);
}
}
转载自:
本文链接:https://blog.csdn.net/Striver00/article/details/116031667
————————————————