import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int a = scanner.nextInt();
scanner.close();
int count = 0;
while (a != 1) {
if (a % 2 == 0) {
a /= 2;
count++;
}
else {
a = (3 * a + 1) / 2;
count++;
}
continue;
}
System.out.print(count);
}
}
这个方法在本题适用
做到后面题的时候由于数值超大,使用Scanner类效率很低会导致运行超时,改用BufferedReader类,直接对输入的字符进行读取、转换。
原因如下:
①BufferedReader是支持同步的,而Scanner不支持
②BufferedReader的缓冲区大小为8KB,Scanner的缓冲区大小为1KB
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
int a = Integer.parseInt(bf.readLine());
int cnt = 0;
while (a != 1) {
if (a % 2 == 0) {
a /= 2;
cnt++;
} else if (a % 2 != 0) {
a = (3 * a + 1) / 2;
cnt++;
}
}
System.out.println(cnt);
}
}
#include<stdio.h>
void Judge(int);
int main(){
int n;
scanf("%d",&n);
Judge(n);
return 0;
}
void Judge(int n){
int cnt = 0;
while(n!=1){
if(n%2){
n = (3*n+1)/2;cnt++;
}
else{
n/=2;cnt++;
}
}
printf("%d\n",cnt);
}