亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Home Java JavaInterview questions A complete collection of Java written test handwritten algorithm interview questions with answers

A complete collection of Java written test handwritten algorithm interview questions with answers

Nov 07, 2019 pm 03:49 PM
java

A complete collection of Java written test handwritten algorithm interview questions with answers

#1. Count the number of words in an English article.

public class WordCounting {
    public static void main(String[] args) {
        try(FileReader fr = new FileReader("a.txt")) {
            int counter = 0;
            boolean state = false;
            int currentChar;
            while((currentChar= fr.read()) != -1) {
                if(currentChar== ' ' || currentChar == '\n'
                        || currentChar == '\t' || currentChar == '\r') {
                    state = false;
                }
                else if(!state) {
                    state = true;
                    counter++;
                }
            }
            System.out.println(counter);
        }
        catch(Exception e) {
            e.printStackTrace();
        }
    }
}

Supplement: This program may be written in many ways. The code chosen here is the code given by teachers Dennis M. Ritchie and Brian W. Kernighan in their immortal book "The C Programming Language" , pay tribute to the two teachers. The same goes for the code below.

2. Enter the year, month and day, and calculate the day of the year that the date is.

public class DayCounting {
    public static void main(String[] args) {
        int[][] data = {
                {31,28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
                {31,29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
        };
        Scanner sc = new Scanner(System.in);
        System.out.print("請(qǐng)輸入年月日(1980 11 28): ");
        int year = sc.nextInt();
        int month = sc.nextInt();
        int date = sc.nextInt();
        int[] daysOfMonth = data[(year % 4 == 0 && year % 100 != 0 || year % 400 == 0)?1 : 0];
        int sum = 0;
        for(int i = 0; i < month -1; i++) {
            sum += daysOfMonth[i];
        }
        sum += date;
        System.out.println(sum);
        sc.close();
    }
}

3. Palindrome prime numbers: The so-called palindrome numbers are the same numbers read forward and backward (for example: 11, 121, 1991...), and palindrome prime numbers are both Palindrome numbers are prime numbers (numbers that are only divisible by 1 and itself). Program to find the palindrome prime numbers between 11 and 9999.

public class PalindromicPrimeNumber {
    public static void main(String[] args) {
        for(int i = 11; i <= 9999; i++) {
            if(isPrime(i) && isPalindromic(i)) {
                System.out.println(i);
            }
        }
    }
    public static boolean isPrime(int n) {
        for(int i = 2; i <= Math.sqrt(n); i++) {
            if(n % i == 0) {
                return false;
            }
        }
        return true;
    }
    public static boolean isPalindromic(int n) {
        int temp = n;
        int sum = 0;
        while(temp > 0) {
            sum= sum * 10 + temp % 10;
            temp/= 10;
        }
        return sum == n;
    }
}

4. Full permutations: Give all permutations of the five numbers 12345.

public class FullPermutation {
    public static void perm(int[] list) {
        perm(list,0);
    }
    private static void perm(int[] list, int k) {
        if (k == list.length) {
            for (int i = 0; i < list.length; i++) {
                System.out.print(list[i]);
            }
            System.out.println();
        }else{
            for (int i = k; i < list.length; i++) {
                swap(list, k, i);
                perm(list, k + 1);
                swap(list, k, i);
            }
        }
    }
    private static void swap(int[] list, int pos1, int pos2) {
        int temp = list[pos1];
        list[pos1] = list[pos2];
        list[pos2] = temp;
    }
    public static void main(String[] args) {
        int[] x = {1, 2, 3, 4, 5};
        perm(x);
    }
}

5. For a one-dimensional array with N integer elements, find the sum of its subarrays (arrays composed of elements with consecutive subscripts in the array) the maximum value.

A few examples are given below (the largest subarray is in bold):

Array: { 1, -2, 3, 5, -3, 2 }, the result is: 8

2) Array: { 0, -2, 3, 5, -1, 2 }, the result is: 9

3) Array: { -9, -2,-3, -5, -3 }, the result is: -2

can be solved using dynamic programming:

public class MaxSum {
    private static int max(int x, int y) {
        return x > y? x: y;
    }
    public static int maxSum(int[] array) {
        int n = array.length;
        int[] start = new int[n];
        int[] all = new int[n];
        all[n - 1] = start[n - 1] = array[n - 1];
        for(int i = n - 2; i >= 0;i--) {
            start[i] = max(array[i], array[i] + start[i + 1]);
            all[i] = max(start[i], all[i + 1]);
        }
        return all[0];
    }
    public static void main(String[] args) {
        int[] x1 = { 1, -2, 3, 5,-3, 2 };
        int[] x2 = { 0, -2, 3, 5,-1, 2 };
        int[] x3 = { -9, -2, -3,-5, -3 };
        System.out.println(maxSum(x1)); // 8
        System.out.println(maxSum(x2)); // 9
        System.out.println(maxSum(x3)); //-2
    }
}

6. Implement string reversal using recursion

public class StringReverse {
    public static String reverse(String originStr) {
        if(originStr == null || originStr.length()== 1) {
            return originStr;
        }
        return reverse(originStr.substring(1))+ originStr.charAt(0);
    }
    public static void main(String[] args) {
        System.out.println(reverse("hello"));
    }
}

7. Enter a positive integer and decompose it into the product of prime numbers.

public class DecomposeInteger {
    private static List<Integer> list = new ArrayList<Integer>();
    public static void main(String[] args) {
        System.out.print("請(qǐng)輸入一個(gè)數(shù): ");
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        decomposeNumber(n);
        System.out.print(n + " = ");
        for(int i = 0; i < list.size() - 1; i++) {
            System.out.print(list.get(i) + " * ");
        }
        System.out.println(list.get(list.size() - 1));
    }
    public static void decomposeNumber(int n) {
        if(isPrime(n)) {
            list.add(n);
            list.add(1);
        }
        else {
            doIt(n, (int)Math.sqrt(n));
        }
    }
    public static void doIt(int n, int div) {
        if(isPrime(div) && n % div == 0) {
            list.add(div);
            decomposeNumber(n / div);
        }
        else {
            doIt(n, div - 1);
        }
    }
    public static boolean isPrime(int n) {
        for(int i = 2; i <= Math.sqrt(n);i++) {
            if(n % i == 0) {
                return false;
            }
        }
        return true;
    }
}

8. There are n steps. You can walk 1, 2 or 3 steps at a time. How many ways can you walk after n steps?

public class GoSteps {
    public static int countWays(int n) {
        if(n < 0) {
            return 0;
        }
        else if(n == 0) {
            return 1;
        }
        else {
            return countWays(n - 1) + countWays(n - 2) + countWays(n -3);
        }
    }
    public static void main(String[] args) {
        System.out.println(countWays(5)); // 13
    }
}

9. Write an algorithm to determine whether all letters of an English word are all different (not case sensitive)

public class AllNotTheSame {
    public static boolean judge(String str) {
        String temp = str.toLowerCase();
        int[] letterCounter = new int[26];
        for(int i = 0; i <temp.length(); i++) {
            int index = temp.charAt(i)- &#39;a&#39;;
            letterCounter[index]++;
            if(letterCounter[index] > 1) {
                return false;
            }
        }
        return true;
    }
    public static void main(String[] args) {
        System.out.println(judge("hello"));
        System.out.print(judge("smile"));
    }
}

10. There is a sorted integer array with duplicate elements. Please delete the duplicate elements. For example, A= [1, 1, 2, 2, 3]. The processed array should be A = [1, 2, 3].

public class RemoveDuplication {
    public static int[] removeDuplicates(int a[]) {
        if(a.length <= 1) {
            return a;
        }
        int index = 0;
        for(int i = 1; i < a.length; i++) {
            if(a[index] != a[i]) {
                a[++index] = a[i];
            }
        }
        int[] b = new int[index + 1];
        System.arraycopy(a, 0, b, 0, b.length);
        return b;
    }
    public static void main(String[] args) {
        int[] a = {1, 1, 2, 2, 3};
        a = removeDuplicates(a);
        System.out.println(Arrays.toString(a));
    }
}

11. Given an array, in which there is a duplicate element accounting for more than half, find this element.

public class FindMost {
    public static <T> T find(T[] x){
        T temp = null;
        for(int i = 0, nTimes = 0; i< x.length;i++) {
            if(nTimes == 0) {
                temp= x[i];
                nTimes= 1;
            }
            else {
                if(x[i].equals(temp)) {
                    nTimes++;
                }
                else {
                    nTimes--;
                }
            }
        }
        return temp;
    }
    public static void main(String[] args) {
        String[]strs = {"hello","kiss","hello","hello","maybe"};
        System.out.println(find(strs));
    }
}

12. Write a method to find the byte length of a string?

public int getWordCount(String s){
    int length = 0;
    for(int i = 0; i < s.length(); i++)
    {
        int ascii = Character.codePointAt(s, i);
        if(ascii >= 0 && ascii <=255)
            length++;
        else
            length += 2;
    }
    return length;
}

The above is the detailed content of A complete collection of Java written test handwritten algorithm interview questions with answers. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1488
72
VSCode settings.json location VSCode settings.json location Aug 01, 2025 am 06:12 AM

The settings.json file is located in the user-level or workspace-level path and is used to customize VSCode settings. 1. User-level path: Windows is C:\Users\\AppData\Roaming\Code\User\settings.json, macOS is /Users//Library/ApplicationSupport/Code/User/settings.json, Linux is /home//.config/Code/User/settings.json; 2. Workspace-level path: .vscode/settings in the project root directory

How to handle transactions in Java with JDBC? How to handle transactions in Java with JDBC? Aug 02, 2025 pm 12:29 PM

To correctly handle JDBC transactions, you must first turn off the automatic commit mode, then perform multiple operations, and finally commit or rollback according to the results; 1. Call conn.setAutoCommit(false) to start the transaction; 2. Execute multiple SQL operations, such as INSERT and UPDATE; 3. Call conn.commit() if all operations are successful, and call conn.rollback() if an exception occurs to ensure data consistency; at the same time, try-with-resources should be used to manage resources, properly handle exceptions and close connections to avoid connection leakage; in addition, it is recommended to use connection pools and set save points to achieve partial rollback, and keep transactions as short as possible to improve performance.

Mastering Dependency Injection in Java with Spring and Guice Mastering Dependency Injection in Java with Spring and Guice Aug 01, 2025 am 05:53 AM

DependencyInjection(DI)isadesignpatternwhereobjectsreceivedependenciesexternally,promotingloosecouplingandeasiertestingthroughconstructor,setter,orfieldinjection.2.SpringFrameworkusesannotationslike@Component,@Service,and@AutowiredwithJava-basedconfi

python itertools combinations example python itertools combinations example Jul 31, 2025 am 09:53 AM

itertools.combinations is used to generate all non-repetitive combinations (order irrelevant) that selects a specified number of elements from the iterable object. Its usage includes: 1. Select 2 element combinations from the list, such as ('A','B'), ('A','C'), etc., to avoid repeated order; 2. Take 3 character combinations of strings, such as "abc" and "abd", which are suitable for subsequence generation; 3. Find the combinations where the sum of two numbers is equal to the target value, such as 1 5=6, simplify the double loop logic; the difference between combinations and arrangement lies in whether the order is important, combinations regard AB and BA as the same, while permutations are regarded as different;

Troubleshooting Common Java `OutOfMemoryError` Scenarios Troubleshooting Common Java `OutOfMemoryError` Scenarios Jul 31, 2025 am 09:07 AM

java.lang.OutOfMemoryError: Javaheapspace indicates insufficient heap memory, and needs to check the processing of large objects, memory leaks and heap settings, and locate and optimize the code through the heap dump analysis tool; 2. Metaspace errors are common in dynamic class generation or hot deployment due to excessive class metadata, and MaxMetaspaceSize should be restricted and class loading should be optimized; 3. Unabletocreatenewnativethread due to exhausting system thread resources, it is necessary to check the number of threads, use thread pools, and adjust the stack size; 4. GCoverheadlimitexceeded means that GC is frequent but has less recycling, and GC logs should be analyzed and optimized.

python pytest fixture example python pytest fixture example Jul 31, 2025 am 09:35 AM

fixture is a function used to provide preset environment or data for tests. 1. Use the @pytest.fixture decorator to define fixture; 2. Inject fixture in parameter form in the test function; 3. Execute setup before yield, and then teardown; 4. Control scope through scope parameters, such as function, module, etc.; 5. Place the shared fixture in conftest.py to achieve cross-file sharing, thereby improving the maintainability and reusability of tests.

Understanding the Java Virtual Machine (JVM) Internals Understanding the Java Virtual Machine (JVM) Internals Aug 01, 2025 am 06:31 AM

TheJVMenablesJava’s"writeonce,runanywhere"capabilitybyexecutingbytecodethroughfourmaincomponents:1.TheClassLoaderSubsystemloads,links,andinitializes.classfilesusingbootstrap,extension,andapplicationclassloaders,ensuringsecureandlazyclassloa

How to work with Calendar in Java? How to work with Calendar in Java? Aug 02, 2025 am 02:38 AM

Use classes in the java.time package to replace the old Date and Calendar classes; 2. Get the current date and time through LocalDate, LocalDateTime and LocalTime; 3. Create a specific date and time using the of() method; 4. Use the plus/minus method to immutably increase and decrease the time; 5. Use ZonedDateTime and ZoneId to process the time zone; 6. Format and parse date strings through DateTimeFormatter; 7. Use Instant to be compatible with the old date types when necessary; date processing in modern Java should give priority to using java.timeAPI, which provides clear, immutable and linear

See all articles