PAT乙级_1001_Java_C(15分)

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);
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值