程序设计基础题库

雅瑗 经验 2024-04-17 472 0
```html Basic Programming Problem Set

Basic Programming Problem Set

Below are some fundamental programming problems along with solutions and explanations:

Description: Write a function that takes two numbers as input and returns their sum.

Solution:

function calculateSum(a, b) {
    return a   b;
}

Explanation: The function simply adds the two input numbers together and returns the result.

Description: Write a function that takes an array of numbers as input and returns the maximum number.

Solution:

function findMax(arr) {
    let max = arr[0];
    for (let i = 1; i < arr.length; i  ) {
        if (arr[i] > max) {
            max = arr[i];
        }
    }
    return max;
}

Explanation: The function iterates through the array, updating the maximum number found so far.

Description: Write a function that takes a number as input and returns true if it's prime, false otherwise.

Solution:

function isPrime(num) {
    if (num <= 1) return false;
    for (let i = 2; i <= Math.sqrt(num); i  ) {
        if (num % i === 0) {
            return false;
        }
    }
    return true;
}

Explanation: The function checks divisibility of the number up to its square root to determine if it's prime.

Description: Write a function that takes a string as input and returns the string reversed.

Solution:

function reverseString(str) {
    return str.split('').reverse().join('');
}

Explanation: The function splits the string into an array of characters, reverses the array, and then joins it back into a string.

Description: Write a function that takes a string as input and returns true if it's a palindrome, false otherwise.

Solution:

function isPalindrome(str) {
    const reversed = str.split('').reverse().join('');
    return str === reversed;
}

Explanation: The function checks if the original string is equal to its reversed form.

```

版权声明

本文仅代表作者观点,不代表百度立场。
本文系作者授权百度百家发表,未经许可,不得转载。

分享:

扫一扫在手机阅读、分享本文

最近发表

雅瑗

这家伙太懒。。。

  • 暂无未发布任何投稿。