【问题标题】:Array Remove last 2 digits of a numberArray 删除数字的最后 2 位数字
【发布时间】:2017-06-01 19:20:22
【问题描述】:

我想创建一个程序,输入一个数字,例如:12345,然后将此数字拆分为2位数字并将其存储在一个数组中。数组必须如下所示: [0]=45 [1]=23 [2]=1 。这意味着数字的拆分必须从数字的最后一位而不是第一位开始。

这是我到现在为止的:

var splitCount = []; // This is the array in which we store our split numbers
//Getting api results via jQuery's GET request
$.get("https://www.googleapis.com/youtube/v3/channels?part=statistics&id=UCJwchuXd_UWNxW-Z1Cg-liw&key=AIzaSyDUzfsMaYjn7dnGXy9ZEtQB_CuHyii4poc", function(result) {
    //result is our api answer and contains the recieved data
    //now we put the subscriber count into another variable (count); this is just for clarity
    count = result.items[0].statistics.subscriberCount;
    //While the subscriber count still has characters
    while (count.length) {
        splitCount.push(count.substr(0, 2)); //Push first two characters into the splitCount array from line 1
        count = count.substr(2); //Remove first two characters from the count string
    }       
    console.log(splitCount) //Output our splitCount array
});

但问题在于,如果有 5 个数字,例如:12345,最后一个数字将单独存在于一个数组中,如下所示:[0]=12 [1]=34 [2]=5 但我需要最后一个数组有 2 个数字,第一个应该是一个数字,而不是像这样:[0]=1 [1]=23 [2]=45

【问题讨论】:

  • 你试过什么?您有任何代码可以向我们展示您已经完成的工作吗?
  • 我们是否假设输入总是整数?
  • 是的,我有这个代码(在上面添加)

标签: javascript arrays split slice digit


【解决方案1】:

我可能会这样做:

int[] fun(int x){
   int xtmp = x;
   int i = 0;
   int len = String.valueOf(x).length(); 
   // this is a function for java, but you can probably find 
   //an equivalent in whatever language you use
   int tab[(len+1)/2];
   while(xtmp > 1){
       tab[i] = xtmp%100;
       xtmp = int(xtmp/100); // here you take the integer part of your xtmp
       ++i;
   }
   return tab;
}

【讨论】:

    【解决方案2】:

    非常粗略,但假设字符串始终是数字,这应该可以工作:

    input = "12345"
    
    def chop_it_up(input)
      o = []
    
      while input.length > 0
        if input.length <= 2
          o << input
        else
          o << input[-2..input.length]
        end
        input = input[0..-3]
        chop_it_up(input)
      end
    
      return o
    end
    

    【讨论】:

    • 我忘了说我在 JS 中需要它
    • 将我用 Ruby 编写的内容转换为 JS 并不难……试一试。
    • 可能不是,但我对编码很陌生,只有 15 岁,我对 Ruby 毫无头绪,目前正在尝试学习 JS。如果您能帮助我,我将非常感激
    • 在这种情况下,您应该将问题标记为 javascript;对不起。相信精通JS的人会愿意帮忙的:)
    • 它是用Javascript标记的
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-13
    • 2015-06-16
    • 1970-01-01
    相关资源
    最近更新 更多