消减整数
题目链接:https://ac.nowcoder.com/acm/contest/11163/C
题目描述
给出一个正整数H,从1开始减,第一次必须减1,每次减的数字都必须和上一次相同或者是上一次的两倍,请问最少需要几次能把H恰好减到0。
输入描述:
第一行给出一个正整数1≤T≤10^4
接下来T行每行一个H,1≤H≤10^9
输出描述:
每行一个正整数代表最少的次数
示例1
输入
3
3
5
7
输出
2
3
3
解题思路:
首先从1开始减,为保证次数最少,之后减的都是2的倍数,如果一开始H为偶数,那么就需要减两次1,如果是奇数就减一次1,用ans计数。
代码如下:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
for (int i = 0; i < t; i++) {
int H = sc.nextInt();
int ans = 0;
while (H > 0) {
if ((H & 1) == 1)
H >>= 1;
else
H--;
ans++;
}
System.out.println(ans);
}
System.out.println();
}
}