自己写算式做比较,4位数以上跟数字作比较会出错

  • 题目要求. You are given two arrays of integers a and b of the same length, and an integer k. We will be iterating through array a from left to right, and simultaneously through array b from right to left, and looking at pairs (x, y), where x is from a and y is from b. Such a pair is called tiny if the concatenation xy is strictly less than k.

Your task is to return the number of tiny pairs that you'll encounter during the simultaneous iteration through a and b.

  • 这个是我写出的
           equation <- function(a, b, k){
              b <- rev(b)
              concat <- numeric(length(a))
              for (i in seq_along(a)){
                concat[i] <- paste0(a[i],b[i])
              }
             test <- concat < k
            result <- sum(test == TRUE)
            result
          }
    
  • 这个代码不能运行4位数以上的array
    三位数test:a<- c(1, 2, 3)
                  b<- c(1, 2, 3)
                  k<- 31
                equation(a, b, k)
    
    运行结果:2
    有四位数test:a <- c(40, 1, 4, 2, 14)
                      b <- c(7, 11, 2, 0, 15)
                      k <- 743
                      equation(a, b, k)
    
    运行结果:5
  • 我不清楚为什么这个算式不对,每一步都没有报错,但是4位数以上的作比较比较不了……
  • 麻烦各位帮我看看哪里不对,哪里需要改进!!麻烦了!!

因为concat里面的东西都是字符串,字符串比较和数值比较的结果是不同的
4015<743是FALSE,但"4015"<743是TRUE
所以在比较前先做个格式转换吧:

test <- as.numeric(concat) < k