VIPKID: pen questions

1. The number of a pair of numbers, and seeking array is 0

Note that you need to use set

import java.util.Scanner;

public class Main{
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        String[] s = sc.nextLine().split(",");
        int len = s.length;
        HashSet<Integer> set = new HashSet<>();
        for (int i = 0; i < len; i++) {
            set.add(Integer.valueOf(s[i].trim()));
        }
        int[] newarray = new int[set.size()];
        int index=0;
        for (Integer i:set) {
            newarray[index++]= i;
        }
        int sum = 0;
        for (int i = 0; i < newarray.length; i++) {
            for (int j = i+1; j < newarray.length; j++) {
                if(newarray[i]+newarray[j]==0){
                    sum++;
                }
            }
        }
        System.out.println(sum);
    }
}

 

2. turn decimal binary number 1

Method 1, to borrow the method java has achieved

import java.util.Scanner;

public class Main{
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        int m = sc.nextInt();
        int num = 0;
        String str = Integer.toBinaryString(m);
        for (int i = 0; i < str.length(); i++) {
            if(str.charAt(i)=='1'){
                num++;
            }
        }
        System.out.println(num);
    }
}

 

Method 2, their implementation is noted that the number of the N-th power of 2 plus 1 requires

import java.util.Scanner;

public class Main{
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        int m = sc.nextInt();
        int num = 0;
        while(m!=0){
            if(m==2){
                num++;
                break;
            }
            if(m%2!=0){
                num++;
            }
            m/=2;
        }
        System.out.println(num);
    }
}

 

Guess you like

Origin www.cnblogs.com/haimishasha/p/11454311.html