【每日一题0925】余数增益

给定一个数字列表nums和一个除数div,我们的任务是将nums中的元素逐个除以除数,得到余数后加在自身,最后返回新的列表。
示例:
nums=[5,6,7],div=3,输出:[7,6,8]。因为余数分别是2,0,1,[5+2, 6+0, 7+1]最终返回[7,6,8]。

题目难度:简单
题目来源:codewars

def add_remainder(nums: list, div:int) -> list:
    pass

assert add_remainder([5, 6, 7], 3) == [7, 6, 8]
assert add_remainder([1000, 999, 998, 997], 5) == [1000, 1003, 1001, 999]
assert add_remainder([2, 7, 5, 9, 100, 34, 32, 0], 3) == [4, 8, 7, 9, 101, 35, 34, 0]
assert add_remainder([], 2) == []
def add_remainder(nums: list, div:int) -> list:
    list1 =nums
    length = len(nums)
    # print(f"length:{length}")
    for i in range(length):
        list1[i] =nums[i]+nums[i] % div
    return list1
def test_add_remainder():
    assert add_remainder([5, 6, 7], 3) == [7, 6, 8]
    assert add_remainder([1000, 999, 998, 997], 5) == [1000, 1003, 1001, 999]
    assert add_remainder([2, 7, 5, 9, 100, 34, 32, 0], 3) == [4, 8, 7, 9, 101, 35, 34, 0]
    assert add_remainder([], 2) == []
def add_remainder(nums: list, div:int) -> list:
    result = nums
    for i in range(len(nums)):
        result[i] = nums[i] + nums[i] % div
    return result

assert add_remainder([5, 6, 7], 3) == [7, 6, 8]
assert add_remainder([1000, 999, 998, 997], 5) == [1000, 1003, 1001, 999]
assert add_remainder([2, 7, 5, 9, 100, 34, 32, 0], 3) == [4, 8, 7, 9, 101, 35, 34, 0]
assert add_remainder([], 2) == []
def add_remainder(nums: list, div:int) -> list:
    list1 = []
    for i in nums:
        vid = int(i) % div
        j = vid + i
        list1.append(j)
    return list1

def test_add_remainder():
    assert add_remainder([5, 6, 7], 3) == [7, 6, 8]
    assert add_remainder([1000, 999, 998, 997], 5) == [1000, 1003, 1001, 999]
    assert add_remainder([2, 7, 5, 9, 100, 34, 32, 0], 3) == [4, 8, 7, 9, 101, 35, 34, 0]
    assert add_remainder([], 2) == []

参考题解:

def add_remainder(nums: list, div:int) -> list:
    return [ n + n % div for n in nums]

assert add_remainder([5, 6, 7], 3) == [7, 6, 8]
assert add_remainder([1000, 999, 998, 997], 5) == [1000, 1003, 1001, 999]
assert add_remainder([2, 7, 5, 9, 100, 34, 32, 0], 3) == [4, 8, 7, 9, 101, 35, 34, 0]
assert add_remainder([], 2) == []

思路:利用列表推导式,一步到位。

public List<Integer> addRemainder(List<Integer> integers, Integer integer) {
        return integers.stream().map(i -> i + i % integer).collect(Collectors.toList());
    }

    @Test
    public void testAddRemainder() {
        assert addRemainder(Arrays.asList(5, 6, 7), 3).equals(Arrays.asList(7, 6, 8));
        assert addRemainder(Arrays.asList(1000, 999, 998, 997), 5).equals(Arrays.asList(1000, 1003, 1001, 999));
        assert addRemainder(Arrays.asList(2, 7, 5, 9, 100, 34, 32, 0), 3).equals(Arrays.asList(4, 8, 7, 9, 101, 35, 34, 0));
        assert addRemainder(Arrays.asList(), 2).equals(Arrays.asList());
    }