本章比較簡單,只挑一些典型題目的java實(shí)現(xiàn)
- 輸入一個(gè)正整數(shù)硬萍,反轉(zhuǎn)其各位的值扩所,然后輸出,比如輸入98765朴乖,輸出56789
public static int reversal(int a){
int value=0;
while (a!=0){
value=value*10+a%10;
a=a/10;
}
return value;
}
- 三整數(shù)排序祖屏,輸入3個(gè)整數(shù)绒障,從小到大排序后輸出懊烤,比如輸入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);
}
- 輸出所有形如aabb的4位完全平方數(shù)
方式一:
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數(shù)值比較大時(shí)缓屠,使用sqrt可能會(huì)產(chǎn)生誤差
方式二:
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);
}
}
方式二通過枚舉方式查找畜普,但顯然循環(huán)次數(shù)比方式一要多很多
注1:
了解一下round方法:
static long round(double a)
此方法返回的參數(shù)最接近的long.
static int round(float a)
此方法返回的參數(shù)最接近的整數(shù).
其四舍五入的原理是在參數(shù)上加0.5然后進(jìn)行下取整
所以也可以改寫為
int n=(int)(Math.floor(Math.sqrt(value)+0.5));