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

首頁(yè) Java Java面試題 java筆試手寫(xiě)演算法面試題大全含答案

java筆試手寫(xiě)演算法面試題大全含答案

Nov 07, 2019 pm 03:49 PM
java

java筆試手寫(xiě)演算法面試題大全含答案

1.統(tǒng)計(jì)一篇英文文章單字?jǐn)?shù)。

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();
        }
    }
}

補(bǔ)充:這個(gè)程式可能有很多種寫(xiě)法,這裡選擇的是Dennis M. Ritchie和Brian W. Kernighan老師在他們不朽的著作《The C Programming Language》中給出的代碼,向兩位老師致敬。下面的程式碼也是如此。

2.輸入年月日,計(jì)算該日期是這一年的第幾天。

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.回文質(zhì)數(shù):所謂回文數(shù)就是順著讀和倒著讀一樣的數(shù)(例如:11,121,1991…),回文素?cái)?shù)就是既是回文數(shù)又是質(zhì)數(shù)(只能被1和自身整除的數(shù))的數(shù)。程式找出11~9999之間的回文素?cái)?shù)。

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.全排列:給出五個(gè)數(shù)字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.對(duì)於一個(gè)有N個(gè)整數(shù)元素的一維數(shù)組,找出它的子數(shù)組(數(shù)組中下標(biāo)連續(xù)的元素所組成的數(shù)組)之和的最大值。

下面給幾個(gè)例子(最大子陣列以粗體表示):

陣列:{ 1, -2, 3, 5, -3, 2 },結(jié)果是:8

2) 陣列:{ 0, -2, 3, 5, -1, 2 },結(jié)果是:9

3)陣列:{ -9, -2,-3, -5, -3 },結(jié)果是:-2

可以使用動(dòng)態(tài)規(guī)劃的想法來(lái)解:

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.用遞迴實(shí)作字串倒轉(zhuǎn)

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.輸入正整數(shù),將其分解為質(zhì)數(shù)的乘積。

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、一個(gè)有n級(jí)的臺(tái)階,一次可以走1級(jí)、2級(jí)或3級(jí),問(wèn)走完n級(jí)臺(tái)階有多少種走法。

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.寫(xiě)一個(gè)演算法判斷一個(gè)英文單字的所有字母是否全都不同(不區(qū)分大小寫(xiě))

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.有一個(gè)已經(jīng)排好序的整數(shù)數(shù)組,其中存在重複元素,請(qǐng)將重複元素刪除掉,例如,A= [1, 1, 2, 2, 3],處理之後的數(shù)組應(yīng)當(dāng)為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.給一個(gè)數(shù)組,其中有一個(gè)重複元素佔(zhàn)半數(shù)以上,找出這個(gè)元素。

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.寫(xiě)一個(gè)方法求一個(gè)字串的位元組長(zhǎng)度?

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;
}

以上是java筆試手寫(xiě)演算法面試題大全含答案的詳細(xì)內(nèi)容。更多資訊請(qǐng)關(guān)注PHP中文網(wǎng)其他相關(guān)文章!

本網(wǎng)站聲明
本文內(nèi)容由網(wǎng)友自願(yuàn)投稿,版權(quán)歸原作者所有。本站不承擔(dān)相應(yīng)的法律責(zé)任。如發(fā)現(xiàn)涉嫌抄襲或侵權(quán)的內(nèi)容,請(qǐng)聯(lián)絡(luò)admin@php.cn

熱AI工具

Undress AI Tool

Undress AI Tool

免費(fèi)脫衣圖片

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅(qū)動(dòng)的應(yīng)用程序,用於創(chuàng)建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費(fèi)的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費(fèi)的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強(qiáng)大的PHP整合開(kāi)發(fā)環(huán)境

Dreamweaver CS6

Dreamweaver CS6

視覺(jué)化網(wǎng)頁(yè)開(kāi)發(fā)工具

SublimeText3 Mac版

SublimeText3 Mac版

神級(jí)程式碼編輯軟體(SublimeText3)

熱門(mén)話題

Laravel 教程
1597
29
PHP教程
1488
72
VSCODE設(shè)置。 JSON位置 VSCODE設(shè)置。 JSON位置 Aug 01, 2025 am 06:12 AM

settings.json文件位於用戶級(jí)或工作區(qū)級(jí)路徑,用於自定義VSCode設(shè)置。 1.用戶級(jí)路徑:Windows為C:\Users\\AppData\Roaming\Code\User\settings.json,macOS為/Users//Library/ApplicationSupport/Code/User/settings.json,Linux為/home//.config/Code/User/settings.json;2.工作區(qū)級(jí)路徑:項(xiàng)目根目錄下的.vscode/settings

如何使用JDBC處理Java的交易? 如何使用JDBC處理Java的交易? Aug 02, 2025 pm 12:29 PM

要正確處理JDBC事務(wù),必須先關(guān)閉自動(dòng)提交模式,再執(zhí)行多個(gè)操作,最後根據(jù)結(jié)果提交或回滾;1.調(diào)用conn.setAutoCommit(false)以開(kāi)始事務(wù);2.執(zhí)行多個(gè)SQL操作,如INSERT和UPDATE;3.若所有操作成功則調(diào)用conn.commit(),若發(fā)生異常則調(diào)用conn.rollback()確保數(shù)據(jù)一致性;同時(shí)應(yīng)使用try-with-resources管理資源,妥善處理異常並關(guān)閉連接,避免連接洩漏;此外建議使用連接池、設(shè)置保存點(diǎn)實(shí)現(xiàn)部分回滾,並保持事務(wù)盡可能短以提升性能。

在Java的掌握依賴注入春季和Guice 在Java的掌握依賴注入春季和Guice Aug 01, 2025 am 05:53 AM

依賴性(di)IsadesignpatternwhereObjectsReceivedenciesenciesExtern上,推廣looseSecouplingAndEaseerTestingThroughConstructor,setter,orfieldInjection.2.springfraMefringframeWorkSannotationsLikeLikeLike@component@component,@component,@service,@autowiredwithjava-service和@autowiredwithjava-ligatiredwithjava-lase-lightike

Python Itertools組合示例 Python Itertools組合示例 Jul 31, 2025 am 09:53 AM

itertools.combinations用於生成從可迭代對(duì)像中選取指定數(shù)量元素的所有不重複組合(順序無(wú)關(guān)),其用法包括:1.從列表中選2個(gè)元素組合,如('A','B')、('A','C')等,避免重複順序;2.對(duì)字符串取3個(gè)字符組合,如"abc"、"abd",適用於子序列生成;3.求兩數(shù)之和等於目標(biāo)值的組合,如1 5=6,簡(jiǎn)化雙重循環(huán)邏輯;組合與排列的區(qū)別在於順序是否重要,combinations視AB與BA為相同,而permutations視為不同;

故障排除常見(jiàn)的java`ofmemoryError`場(chǎng)景'' 故障排除常見(jiàn)的java`ofmemoryError`場(chǎng)景'' Jul 31, 2025 am 09:07 AM

java.lang.OutOfMemoryError:Javaheapspace表示堆內(nèi)存不足,需檢查大對(duì)象處理、內(nèi)存洩漏及堆設(shè)置,通過(guò)堆轉(zhuǎn)儲(chǔ)分析工具定位並優(yōu)化代碼;2.Metaspace錯(cuò)誤因類元數(shù)據(jù)過(guò)多,常見(jiàn)於動(dòng)態(tài)類生成或熱部署,應(yīng)限制MaxMetaspaceSize並優(yōu)化類加載;3.Unabletocreatenewnativethread因係統(tǒng)線程資源耗盡,需檢查線程數(shù)限制、使用線程池、調(diào)整棧大小;4.GCoverheadlimitexceeded指GC頻繁但回收少,應(yīng)分析GC日誌,優(yōu)化

Python Pytest夾具示例 Python Pytest夾具示例 Jul 31, 2025 am 09:35 AM

fixture是用於為測(cè)試提供預(yù)設(shè)環(huán)境或數(shù)據(jù)的函數(shù),1.使用@pytest.fixture裝飾器定義fixture;2.在測(cè)試函數(shù)中以參數(shù)形式註入fixture;3.yield之前執(zhí)行setup,之後執(zhí)行teardown;4.通過(guò)scope參數(shù)控製作用域,如function、module等;5.將共用fixture放在conftest.py中實(shí)現(xiàn)跨文件共享,從而提升測(cè)試的可維護(hù)性和復(fù)用性。

了解Java虛擬機(jī)(JVM)內(nèi)部 了解Java虛擬機(jī)(JVM)內(nèi)部 Aug 01, 2025 am 06:31 AM

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

如何使用Java的日曆? 如何使用Java的日曆? Aug 02, 2025 am 02:38 AM

使用java.time包中的類替代舊的Date和Calendar類;2.通過(guò)LocalDate、LocalDateTime和LocalTime獲取當(dāng)前日期時(shí)間;3.使用of()方法創(chuàng)建特定日期時(shí)間;4.利用plus/minus方法不可變地增減時(shí)間;5.使用ZonedDateTime和ZoneId處理時(shí)區(qū);6.通過(guò)DateTimeFormatter格式化和解析日期字符串;7.必要時(shí)通過(guò)Instant與舊日期類型兼容;現(xiàn)代Java中日期處理應(yīng)優(yōu)先使用java.timeAPI,它提供了清晰、不可變且線

See all articles