1、要求计算1!+2!+……10!的值
第一种是for循环:
- public class TestXiti {
- public static void main(String[] args) {
- double sum=0.0;
- for(int i=0;i<=10;i++) {
- double temp=1.0;
- for(int j=1;j<=i;j++) {
- temp=temp*j;
- }
- sum+=temp;
- }
- System.out.println(sum);
- }
- }
第二种是递归:
- public class TestXiti {
- public static void main(String[] args) {
- System.out.println(mul(10));
- }
- public static double mul(int num) {
- if(num==1) {
- return fun(1);
- }
- return fun(num) +mul(num-1);
- }
- public static double fun(int num) {
- if(num==1) {
- return 1;
- }
- return num*fun(num-1);
- }
- }
2、编写一个方法,此方法可以将一个整数二进制输出:
- //for循环
- public class TestXiti {
- public static void main(String[] args) {
- int t=11;
- String str="";
- while(t!=0) {
- str=(t%2)+str;
- t=t/2;
- }
- System.out.println(str);
- }
- }
- //递归
- public class TestXiti {
- public static void main(String[] args) {
- toBanary(11);
- }
- public static void toBanary(int num ) {
- if(num/2==0) {
- System.out.print(num%2);
- }
- else {
- toBanary(num/2);
- System.out.print(num%2);
- }
-
- }
- }
3、先给出2个数组,将2个数组合并后,升序输出:
数组A {1,7,9,11,13,15,17,19};
数组B {2,4,6,8,10};
- public class TestXiti {
- public static void main(String[] args) {
- int dataA[]=new int[] {1,7,9,11,13,15,17,19};
- int dataB[]=new int[] {2,4,6,8,10};
- int dataC[]=contact(dataA,dataB);
- java.util.Arrays.sort(dataC);
- print(dataC);
- }
- public static int[] contact(int arrA[],int arrB[]) {
- int arrC []=new int[arrA.length+arrB.length];
- System.arraycopy(arrA, 0, arrC, 0, arrA.length);
- System.arraycopy(arrB, 0, arrC, arrA.length, arrB.length);
- return arrC;
- }
- public static void print(int [] arr) {
- for(int x=0;x<arr.length;x++) {
- System.out.print(arr[x] + " ");
- }
- }
- }
4、//数组转置
public class TestXiti {
public static void main(String[] args) {
int data[]=new int[] {1,2,3,4,5,6};
reverse(data);
print(data);
}
public static void reverse(int [] temp) {
int center=temp.length / 2;
int head=0;
int tail=temp.length-1;
for(int x=0;x
int t=temp[head];
temp[head]=temp[tail];
temp[tail]=t;
head++;
tail--;
}
}
public static void print(int [] arr) {
for(int x=0;xlength;x++) {
System.out.print(arr[x] + " ");
}
}
}
5、去掉数组中的0;
public class TestXiti {
public static void main(String[] args) {
int oldArr[]=new int[] {1,3,4,5,0,0,6,6,0,5,4,7,6,7,0,5};
int newArr[]=new int[count(oldArr)];
copy(oldArr,newArr);
print(newArr);
}
public static int count(int arr[]) {
int sum=0;
for(int i=0;ilength;i++) {
if(arr[i]!=0)
sum++;
}
return sum;
}
public static void copy(int oldArr [] , int newArr []) {
int foot=0;
for(int i=0;ilength;i++) {
if(oldArr[i]!=0) {
newArr[foot++]=oldArr[i];
}
}
}
public static void print(int [] arr) {
for(int x=0;xlength;x++) {
System.out.print(arr[x] + " ");
}
}
}
阅读(1776) | 评论(0) | 转发(0) |