java实现:PAT-B 1001. 害死人不偿命的(3n+1)猜想 (15)、PAT-B 1002. 写出这个数 (20)

题目:1001. 害死人不偿命的(3n+1)猜想

卡拉兹(Callatz)猜想:
对任何一个自然数n,如果它是偶数,那么把它砍掉一半;如果它是奇数,那么把(3n+1)砍掉一半。这样一直反复砍下去,
最后一定在某一步得到n=1。卡拉兹在1950年的世界数学家大会上公布了这个猜想,传说当时耶鲁大学师生齐动员,
拼命想证明这个貌似很傻很天真的命题,结果闹得学生们无心学业,一心只证(3n+1),以至于有人说这是一个阴谋,
卡拉兹是在蓄意延缓美国数学界教学与科研的进展……
我们今天的题目不是证明卡拉兹猜想,而是对给定的任一不超过1000的正整数n,简单地数一下,需要多少步(砍几下)才能得到n=1?

输入格式:

每个测试输入包含1个测试用例,即给出自然数n的值。

输出格式:

输出从n计算到1需要的步数。

输入样例:

3

输出样例:

5

分析

这道题需要用while循环对n进行判断,每次n按照题目要求进行运算,每运算一次,给计数器变量自增1,直到n为1时,停止循环,输出计数器变量即可。


import java.util.Scanner;

/**
 *
 * @author biubiubiu
 */
public class GradeB1001 {
    public static void main(String[] args) {
        System.out.print("请输入一个1000以内的正整数n:");
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int count = 0;
        if (n >= 0 && n < 1000) {
            while (n != 1) {
                if (n % 2 == 0) {
                    n = n / 2;
                    count++;
                } else {
                    n = (3 * n + 1) / 2;
                    count++;
                }
            }
        }else {
            System.out.println("您的输入有误~");
        }
        System.out.println("count:" + count);
    }
}

题目:1002. 写出这个数

读入一个自然数n,计算其各位数字之和,用汉语拼音写出和的每一位数字。
输入格式:每个测试输入包含1个测试用例,即给出自然数n的值。这里保证n小于10100。

输出格式:

在一行内输出n的各位数字之和的每一位,拼音数字间有1 空格,但一行中最后一个拼音数字后没有空格。

输入样例:

1234567890987654321123456789

输出样例:

yi san wu

分析

Java实现方法是:
1.读入一行字符串,然后将字符串转为char数组;
2.将char数组的每位转为int型,这里注意要减去0的ASCII码为48,然后相加起来;
3.然后将和再转为char数组,根据每位的数字,输出对应的拼音即可,需要注意的是最后没有空格。

import java.util.Scanner;

/**
 *
 *
 * @author biubiubiu
 */
public class GradeB1002 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String s1 = sc.next();
        char[] c1 = s1.toCharArray();
        int sum = 0;
        for(int i=0; i<c1.length; i++){
            sum += c1[i] - 48;
        }
        String s2 = String.valueOf(sum);
        char[] c2 = s2.toCharArray();
        for(int i=0; i<c2.length; i++){
            if(c2[i] == '1'){
                System.out.print("yi");
            }else if (c2[i] == '2'){
                System.out.print("er");
            }else if (c2[i] == '3'){
                System.out.print("san");
            }else if (c2[i] == '4'){
                System.out.print("si");
            }else if (c2[i] == '5'){
                System.out.print("wu");
            }else if (c2[i] == '6'){
                System.out.print("liu");
            }else if (c2[i] == '7'){
                System.out.print("qi");
            }else if (c2[i] == '8'){
                System.out.print("ba");
            }else if (c2[i] == '9'){
                System.out.print("jiu");
            }else {
                System.out.print("ling");
            }
            if(i < c2.length-1){
                System.out.print(" ");
            }
        }
    }
}

发布了108 篇原创文章 · 获赞 39 · 访问量 9362

猜你喜欢

转载自blog.csdn.net/qq_40246175/article/details/102878042
今日推荐