[codewars][python][C++]Even numbers in an array

本文介绍了一种从给定的数字数组中提取最后N个偶数的方法,并提供了Python和C++的实现代码。通过倒序遍历数组,算法能够有效地找到所需的偶数并按原顺序返回。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given an array of digitals numbers, return a new array of length number containing the last even numbers from the original array (in the same order). The original array will be not empty and will contain at least "number" even numbers.

For example:

([1, 2, 3, 4, 5, 6, 7, 8, 9], 3) => [4, 6, 8]
([-22, 5, 3, 11, 26, -6, -7, -8, -9, -8, 26], 2) => [-8, 26]
([6, -25, 3, 7, 5, 5, 7, -3, 23], 1) => [6]

思路:倒序遍历整个数组,找到n个的偶数即可

代码如下:

【python】

def even_numbers(arr,n):
    ret=[]
    if n<=0:
        return ret
    for i in range(len(arr)):
        temp=arr[len(arr)-i-1]
        if temp%2==0:
            ret.insert(0,temp)
            n-=1
            if n<=0:
                break
    return ret

【C++】

std::vector<int> evenNumbers(std::vector<int> arr, int n) {
    //your code here
    std::vector<int> a;
    if (n <= 0)
    {
        return a;
    }
    int len = arr.size();
    for (int i = 0; i < arr.size(); i++)
    {
        if (arr[len-i-1] % 2 == 0)
        {
            a.insert(a.begin(), arr[len-i-1]);
            n--;
            if (n <= 0)
            {
                break;
            }
        }
    }
    return a;
}

### Logical AND Operator Usage in Programming Code Examples The logical AND (`&&`) operator evaluates two conditions and returns true only when both operands are true. In many programming languages such as C++, Java, JavaScript, this operator plays an essential role in conditional statements and loops. #### Conditional Statements with `&&` For instance, consider checking multiple conditions within an if statement: ```cpp if (age >= 18 && age <= 65) { std::cout << "Eligible for employment."; } ``` This snippet checks whether the variable `age` lies between 18 and 65 inclusive[^1]. #### Filtering DataFrames Using `&` Equivalent to `&&` When working with pandas DataFrame objects in Python, one might use the `&` operator instead of `&&`, which serves similarly by performing element-wise logical AND operations across boolean arrays created through comparisons: ```python import pandas as pd data = {'name': ['Alice', 'Bob', 'Charlie'], 'age': [25, 30, 35], 'salary': [70_000, 90_000, 110_000]} df = pd.DataFrame(data) filtered_df = df[(df['age'] > 25) & (df['salary'] < 100_000)] print(filtered_df) ``` Here, parentheses ensure correct precedence while combining different criteria into a single filter condition[^2]. #### Combining Conditions Within Loops Using `&&` inside loop structures allows more complex logic control flow: ```java for (int i = 0; i < array.length; ++i) { if (!(array[i] % 2 == 0 && array[i] != 0)) continue; System.out.println(array[i]); } ``` In this example, even numbers except zero get printed out due to combined negation and conjunction operation applied over elements during iteration. --related questions-- 1. How does short-circuit evaluation work with the logical AND operator? 2. What differences exist between bitwise AND (`&`) versus logical AND (`&&`) operators? 3. Can you provide scenarios where using nested ternary operators alongside `&&` could simplify code readability? 4. Are there performance implications associated with frequent usage of `&&` compared to other forms of branching constructs?
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值