首页 > 编程语言 >【LeetCode2180】[Go/C++/C#/Ruby/Swift/Kotlin/Rust/PHP/TS/Racket/Dart/Java/Elixir/Scala/Erlang] 统计各位数字之

【LeetCode2180】[Go/C++/C#/Ruby/Swift/Kotlin/Rust/PHP/TS/Racket/Dart/Java/Elixir/Scala/Erlang] 统计各位数字之

时间:2023-01-06 10:24:27浏览次数:82  
标签:count Java Scala int sum num return div Erlang

[toc]

题解地址

https://leetcode.cn/problems/count-integers-with-even-digit-sum/solutions/2047123/by-yhm138_-w8co/ lc2180

代码

//点击指定元素
document.querySelector("#__next > div > div > div > div > div > div > div > div.shadow-level1.dark\\:shadow-dark-level1.flex.w-full.min-w-0.flex-col.rounded-xl.lc-lg\\:max-w-\\[700px\\].bg-layer-1.dark\\:bg-dark-layer-1 > div.relative.flex.w-full.flex-col > div.flex.w-full.flex-col.gap-4.px-5.pt-4.pb-8 > div.break-words > div > div > div > div.flex.select-none.bg-layer-2.dark\\:bg-dark-layer-2 > div:nth-child(13)").click();
//我的问题是,Go支持函数式编程吗?

func countEven(num int) int {
    a := makeRange(1, num)
    evenCount := len(filter(a, func(num int) bool {
        numStr := strconv.Itoa(num)
        digits := strings.Split(numStr, "")
        mySum:=0
        for _,ele :=range digits{
            d, _ := strconv.Atoi(ele)
            mySum=mySum+d
        }
        return mySum%2 == 0
    }))
    return evenCount
}


func filter(src []int, p func(int) bool) []int {
	dst := []int{}
	for _, s := range src {
		if p(s) {
			dst = append(dst, s)
		}
	}
	return dst
}

func makeRange(min, max int) []int {
    a := make([]int, max-min+1)
    for i := range a {
        a[i] = min + i
    }
    return a
}


//C++
class Solution {
public:
    int countEven(int num) {
        std::vector<int> range(num);
        std::iota(range.begin(), range.end(), 1);
        return std::count_if(range.begin(), range.end(), [](int x) {
            std::string str = std::to_string(x);
            return std::accumulate(str.begin(), str.end(), 0, [](int sum, char c) {
                return sum + (c - '0');
            }) % 2 == 0;
        });
    }
};
//C#
using System;
using System.Linq;

public class Solution {
    public int CountEven(int num) {
         return Enumerable.Range(1, num).Count(x => x.ToString().Select(c => c - '0').Sum() % 2 == 0);
    }
}
# ruby

# @param {Integer} num
# @return {Integer}
def count_even(num)
  (1..num).count { |x| x.to_s.chars.map(&:to_i).sum % 2 == 0 }
end
//swift

class Solution {
    func countEven(_ num: Int) -> Int {
        return (1...num).filter { x in
            x.description.map { Int(String($0))! }.reduce(0, +) % 2 == 0
        }.count
    }
}
//kotlin

class Solution {
    fun countEven(num: Int): Int {
        return (1..num).count {
            it.toString().toList().map { it.toInt() }.sum() % 2 == 0
        }
    }
}
//rust

impl Solution {
    pub fn count_even(num: i32) -> i32 {
        (1..num+1).filter(|x| x.to_string().chars().map(|c| c.to_digit(10).unwrap()).sum::<u32>() % 2 == 0)
                  .count() as i32
    }
}

//php

class Solution {

    /**
     * @param Integer $num
     * @return Integer
     */
    function countEven($num) {
        $result = array_filter(range(1, $num), function($x) {
            $sum = 0;
            foreach(str_split((string)$x) as $digit) {
                $sum += intval($digit);
            }
            return $sum % 2 == 0;
        });
        return count($result);
    }

}
//typescript

function countEven(num: number): number {
    return Array.from(Array(num).keys())
        .map(x => x + 1)
        .filter(x => x.toString()
            .split('')
            .map(Number)
            .reduce((a, b) => a + b, 0) % 2 === 0)
        .length;
}
;racket

(define/contract (count-even num)
  (-> exact-integer? exact-integer?)
    (length
        (filter (lambda (x)
                (even? (apply + (map char->integer (string->list (number->string x))))))
            (range 1 (add1 num))
        )
    )
)
//dart

class Solution {
  int countEven(int num) {
    return Iterable.generate(num, (x) => x+1)
        .where((x) => 
            x.toString().split('').map(int.parse).reduce((a,b) => a+b) % 2 == 0
        ).length;
    }
}
//java

import java.util.stream.IntStream;

public class Solution {
    public static int countEven(int num) {
        return (int) IntStream.range(1, num+1).filter(x -> 
            IntStream.range(0, String.valueOf(x).length())
                .map(y -> Character.getNumericValue(String.valueOf(x).charAt(y)))
                .sum() % 2 == 0
        ).count();
    }
}

#elixir

defmodule Solution do
  @spec count_even(num :: integer) :: integer
  def count_even(num) do
    (1..num)|> 
        Enum.count(fn x ->
             x |> Integer.to_string() |> String.graphemes() |> Enum.map(&String.to_integer/1) |> Enum.sum() |> rem(2) == 0
        end)
  end
end
//scala

object Solution {
    def countEven(num: Int): Int = {
        Range(1,num+1,1).count(x=>{
            x.toString.toList.map(_.toInt).sum%2==0
        });
    }
}
%erlang

sum_digits(N) ->
    sum_digits(N, 0).

sum_digits(0, Sum) -> Sum;
sum_digits(N, Sum) ->
    sum_digits(N div 10, Sum + N rem 10).


-spec count_even(Num :: integer()) -> integer().
count_even(Num) ->
    lists:foldl(fun(X, Acc) ->
                    Sum = sum_digits(X),
                    if Sum rem 2 == 0 ->
                        Acc + 1;
                    true ->
                        Acc
                    end
                end, 
    0,  [X || X <- lists:seq(1, Num)]).
    

思路

有些是拿适当的prompt问chatgpt写的。
有一些tips:

  • chatgpt是真的强,没人比chatgpt更懂FP     :-p

  • chatgpt分不清不同语言的Range/range是左闭右开还是左闭右闭。没事,人类也记不住。

  • elixir的时候,chatgpt给出的答案中,匿名函数fn没有和end配对。你如果知道基础的elixir语法那很好改。

  • 不知道也没事?直接拿你的代码附上报错直接问chatgpt。

correct the erlang code
sum_digits(N) ->
    sum_digits(N, 0).

sum_digits(0, Sum) -> Sum;
sum_digits(N, Sum) ->
    sum_digits(N div 10, Sum + N rem 10).


-spec count_even(Num :: integer()) -> integer().
count_even(Num) ->
    lists:foldl(fun(X, Acc) ->
                    if sum_digits(X) rem 2 == 0 ->
                        Acc + 1;
                    true ->
                        Acc
                    end
                end, 
    0,  [X || X <- lists:seq(1, Num)]).


    
Line 13: Char 24: call to local/imported function sum_digits/1 is illegal in guard
%   13|                     if sum_digits(X) rem 2 == 0 ->
%     |                        ^

)

标签:count,Java,Scala,int,sum,num,return,div,Erlang
From: https://www.cnblogs.com/yhm138/p/17029417.html

相关文章

  • Java调用CMD命令
    ProcessBuilderbuilder= newProcessBuilder(commands);1、在使用ProcessBuilder时,如果commands使用{"java-version"}这种带空格的命令,可能会报文件找不到的错误,最......
  • [Java 8] (1) 函数式编程简介
    思维方式的转变以从一个城市集合中寻找是否存在Chicago为例:习惯的方式booleanfound=false;for(Stringcity:cities){if(city.equals("Chicago")){......
  • JAVA常用的工具类
    1集合工具类1.1java.util.Collections使用的基本list示意List<Integer>list=newArrayList<>();list.add(2);list.add(1);list.add(3);1.1.1基本操作Collections.so......
  • JAVA调用SAP RFC接口
    java要调用SAPRFC接口时,需要用到sapjco3.jar架包;windows下还需要将文件sapjco3.dll文件放到system32的目录下;linux下同样需要把sapjco3.so放入项目的执行目录下;下载......
  • JAVA获取上下行网速
    packagecom.iecas.zwterminalstate.util;importjava.io.BufferedReader;importjava.io.IOException;importjava.io.InputStreamReader;importjava.util.Formatter;imp......
  • 【Java】线程池梳理
    【Java】线程池梳理前言线程池:本质上是一种对象池,用于管理线程资源。在任务执行前,需要从线程池中拿出线程来执行。在任务执行完成之后,需要把线程放回线程池。通过线程的......
  • java -jar 指定logback.xml、application.yaml
    java-jar指定logback.xml -Dlogging.config="C:\logbacs\logback.xml"示例:java-jar  -Dlogging.config="/home/yqq/config/logback.xml" zwdatagather-1.0.0......
  • Java面试题Day03
    1.HashMap的resize过程是什么样的?采用hash表数据加链表的形式,1.8以后引入了红黑树的数据结构,初始化数组长度为16,当数组长度到0.75时扩容,链表长度大于8时转为红黑树,......
  • 【一句话】JAVA8后abstract class和interface的区别
    首先一句话:JAVA8后(1)interface支持default和static方法有实现,abstractclass依然是抽象方法和非抽象方法,(2)可同时实现多个interface,(3)但成员变量只能是staticfanal的......
  • JAVA中使用最广泛的本地缓存?Ehcache的自信从何而来3 —— 本地缓存变身分布式集群缓存
    大家好,又见面了。本文是笔者作为掘金技术社区签约作者的身份输出的缓存专栏系列内容,将会通过系列专题,讲清楚缓存的方方面面。如果感兴趣,欢迎关注以获取后续更新。上......