一、java实现输出从1到n的所有质数
1、质数的特点就是只能被1和其本身整除。
public static int[] getAllPrimeNumber(int n){
int[] retArr=new int[n];
boolean isPrime;
for(int i=1;i<n;i++){
isPrime=true;
for(int j=2;j<i;j++){
if(i%j==0){
isPrime=false;
break;
}
}
if(isPrime){
retArr[i]=i;
}
}
return retArr;
}
2、平方根或1/2:
public class Prime {
public static void main(String[] args) {
for(int j = 2; j<n; j++){
if(m(j)){
System.out.print(j+" ");
}
}
}
public static boolean m(int num){
for(int j = 2; j<=Math.sqrt(num);j++){
二、链表中。两个Node相加 ,实现:Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8:
public class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode sum = new ListNode(0);
ListNode temp = sum;
int i=0;
while(l1!=null ||l2!=null||i!=0){
if(l1==null){
l1 = new ListNode(0);
}
if(l2 == null){
l2 = new ListNode(0);
}
if(sum==null){
sum = new ListNode(0);
}
if(l1.val+l2.val+i<10){
sum.next = new ListNode(l1.val+l2.val+i);
sum = sum.next;
i=0;
}else{
sum.next = new ListNode(l1.val+l2.val+i-10);
sum = sum.next;
i=1;
}
l1 = l1.next;
l2 = l2.next;
}
return temp.next;
}
}