题
正整数取出每一位放到数组中
package test;
import java.util.Arrays;
import java.util.Scanner;
/**
* 正整数取出每一位放到数组中
*/
public class Demo1 {
public static void main(String[] args) {
while (true) {
int num = new Scanner(System.in).nextInt();
int[] array = toArrays(num);
System.out.println(Arrays.toString(array));
}
}
public static int[] toArrays(int num) {
//临时变量,接收整数,做后续处理
int temp = num;
//最后要返回的数组(待返回数组)
int[] array;
//计算整数的位数
int account = 1;
while (temp > 10) {
account++;
temp /= 10;//temp会不停改变
}
//确定待返回数组的大小
array = new int[account];
//对num每次%10得到整数的每一位(从低到高),倒序填入待返回数组
while (account > 0) {
array[account - 1] = num % 10;
num /= 10;
account--;
}
return array;
}
}
合并2个有序数组(从小到大)为一个有序数组
package test;
import java.util.Arrays;
/**
* 合并2个有序数组(从小到大)为一个有序数组
*/
public class Demo2 {
public static void main(String[] args) {
int[] array1 = {1, 3, 5, 7, 10};
int[] array2 = {2, 4, 6, 8, 9};
int[] array = fun(array1, array2);
System.out.println(Arrays.toString(array));
}
public static int[] fun(int[] array1, int[] array2) {
//记录2个数组的总长度
int length1 = array1.length;
int length2 = array2.length;
int account = length1 + length2;
//最后要返回的数组(待返回数组)
int[] array = new int[account];
//分别记录array1和array2当前待比较的位置
int i1 = 0;
int i2 = 0;
//记录待返回数组array当前要插入数据的位置
int i = 0;
//比较、填值
while (i1 < length1 && i2 < length2) {
if (array1[i1] < array2[i2]) {
array[i] = array1[i1];
i1++;
i++;
} else {
array[i] = array2[i2];
i2++;
i++;
}
}
while (i1 < length1) {
array[i] = array1[i1];
i1++;
i++;
}
while (i2 < length2) {
array[i] = array2[i2];
i2++;
i++;
}
return array;
}
}
求斐波那契数列{1,1,2,3,5,8} 第n项的值
package test;
import sun.print.SunMinMaxPage;
/**
* 求斐波那契数列{1,1,2,3,5,8} 第n项的值
*/
public class Demo4 {
public static void main(String[] args) {
System.out.println(fun(3));
}
public static int fun(int n) {
if (n == 1 || n == 2) {
return 1;
}
int before = 1;
int after = 1;
for (int i = 1; i <= n - 2; i++) {
int temp = after;
after += before;
before = temp;
}
return after;
}
}