[JAVA] Thuật toán kiểm tra tồn tại bao nhiêu số 1 có trong một số nguyên dương bất kỳ.

[JAVA] Thuật toán kiểm tra tồn tại bao nhiêu số 1 có trong một số nguyên dương bất kỳ.

Yêu cầu 1 : Cho 1 số nguyên bất kỳ đếm bao nhiêu số 1.

Input : số nguyên 12811381

Output : 4 số 1.

Phân tích : áp dụng phương pháp chia lấy phần nguyên và chia lấy dư như dưới ta có thể đếm được bao nhiêu số 1 trong 1 số nguyên bất kỳ.

java1.PNG


public class NumberCount {

    public static void main(String[] args) {

        Integer inputNumber = 12811381;
        int cloneinputNumber =  12811381;
        int count = 0;

        while(inputNumber != 0) {    

            int remainder = inputNumber % 10; // chia lấy dư
            inputNumber = inputNumber /  10;  // chia lấy phần nguyên

            if(remainder ==  1)
                count ++;
        }

        System.out.println("Trong số nguyên : "+ cloneinputNumber+ " ta đếm được "+ count + " số 1");
    }

}

Kết quả :

image.png Yêu cầu 2 : Tạo mãng số nguyên gồm 6 phần tử, giá trị của mỗi phần tử ngẫu nhiêu, đếm có bao nhiêu số 1 trong mỗi phần tử.

Phân tích:

  • khởi tạo : array A[6],
  • khở tạo giá trị cho mỗi phần tử trong array A
  • Đếm mỗi phần tử có bao nhiêu số 1 áp dụng thuật toán yêu cần 1.
import java.util.HashMap;
import java.util.concurrent.ThreadLocalRandom;

public class NumberCountInArray {

    private static int countNumberOne (Integer number) {
        int count = 0; 
        while(number != 0) {
            Integer remainder = number % 10;
            number = number / 10;
            if (remainder == 1) {
                count ++;
            }
        }
        return count;
    }

    public static void main(String[] args) {
        int A [] = new int[6];

        // khởi tạo giá trị cho mãng A
        for (int i = 0; i < A.length; i++) {
            // tạo số nguyên ngẫu nhiều từ 10000 -> 999999999
            int randomIntNumber = ThreadLocalRandom.current().nextInt(10000,999999999);
            A[i] = randomIntNumber;
        }

        String StringArrayA = "A [] = { ";
        for (int i = 0; i < A.length; i++) {
            if(i == A.length - 1) {
                StringArrayA = StringArrayA.concat(A[i]+" }");
            }else {
                StringArrayA = StringArrayA.concat(A[i]+" ,");
            }
        }
        System.out.println("Mãng sau khi được khởi tạo.");
        System.out.println(StringArrayA);

        // Print output
        HashMap<String, Integer> valueOuput = new HashMap<String, Integer>();

        for (int i = 0; i < A.length; i++) {
            valueOuput.put("A["+i+ "] = " + A[i] + "", NumberCountInArray.countNumberOne(A[i]));
        }

        valueOuput.forEach((k,v)-> System.out.println("Trong số nguyên : "+k+ " ta đếm được " +v+ " số 1"));
    }

}

Kết quả:

image.png

Did you find this article valuable?

Support VÕ VĂN TRINH by becoming a sponsor. Any amount is appreciated!