第一至三章

2019-07-24  本文已影响0人  古剑诛仙

本章比较简单,只挑一些典型题目的java实现

  1. 输入一个正整数,反转其各位的值,然后输出,比如输入98765,输出56789
 public static int reversal(int a){
        int value=0;
        while (a!=0){
            value=value*10+a%10;
            a=a/10;

        }
        return value;
    }
  1. 三整数排序,输入3个整数,从小到大排序后输出,比如输入7,11,3,输出3,7,11
public static void  threesort(int a,int b,int c){
        int temp;
        if(a>b){
            temp=a;
            a=b;
            b=temp;
        }// a<=b
        if(b>c){
            temp=b;
            b=c;
            c=temp;
        }// b<=c
        if(a>c){
            temp=a;
            a=c;
            c=temp;
        }// a<=c
        System.out.println(a+","+b+","+c);

    }
  1. 输出所有形如aabb的4位完全平方数
方式一:
 public static void  getaabb1(){
        for(int i=1;i<10;i++)
            for(int j=0;j<10;j++){
                int value=i*1100+j*11;
                int n=Math.round((float)(Math.sqrt(value)));// 注1

                if(n*n==value)
                    System.out.println(value);
            }
    }
方式一在value数值比较大时,使用sqrt可能会产生误差
方式二:
public static void  getaabb2(){
        for(int i=1;;i++){
            int n=i*i;
            if(n<1000)continue;
            if(n>9999)break;
            int high=n/100;
            int low=n%100;
            if(high/10==high%10&&low/10==low%10)
                System.out.println(n);
        }
    }
方式二通过枚举方式查找,但显然循环次数比方式一要多很多

注1:
了解一下round方法:

static long round(double a) 
此方法返回的参数最接近的long. 
static int round(float a) 
此方法返回的参数最接近的整数.

其四舍五入的原理是在参数上加0.5然后进行下取整
所以也可以改写为
int n=(int)(Math.floor(Math.sqrt(value)+0.5));
上一篇 下一篇

猜你喜欢

热点阅读