【问题标题】:How to increment a char int array inside a 'for-loop'如何在“for-loop”中增加 char int 数组
【发布时间】:2018-09-15 02:41:21
【问题描述】:

在过去的 2 个小时里,我一直在绞尽脑汁想弄清楚我的代码出了什么问题。它应该是加密系统的小私钥的暴力算法;

public static char[] Increment(char[] a, int b, char c) {
    if (a[b] < c)
        a[b] += 1;
    else if ((b) > 0) {
        a[b] = '0';
        Increment(a, b-1, c);
    }
    return a;
} 

public static BigInteger StringLayer(char[] str, char[] a) {

    int index = 0;
    for (int i = 0; i < str.length; i++) {
        if (str[i] == '-') {
            str[i] = a[index];
            index++;
        }
    }
    return new BigInteger(new String(str));
}


public static void main(String[] args) {

    char[] Store = {'0', '0', '0', '0'};

    char[] ab1 = {'4', '-', '-', '7', '8', '-', '3', '0', '-'};

    for (int i = 0; i < 10000; i++) {

        Store = Increment(Store, Store.length - 1, '9');
        System.out.println(Store);
        System.out.println(StringLayer(ab1, Store));
    }

输出的摘录如下;

0001

400780301

0002

400780301

0003

400780301

等等

我不知道为什么增加的 Store 变量(在输出中似乎在增加)在传递给 StringLayer 方法时不会增加。我确信答案非常简单,我错过了一些我应该 100% 知道的东西,但我真的很难过,希望能提供任何帮助。

【问题讨论】:

    标签: java arrays string loops increment


    【解决方案1】:

    答案很简单,但很棘手。当您将 ab1 传递给您的 StringLayer 方法时,您将传递 reference 因此通过替换所有 - 来修改 original 数组。所以在第一次调用之后,ab1 数组中不再有 -。为了防止这种情况,您应该在处理之前创建数组的副本:

      public static BigInteger StringLayer( char[] str, char[] a )
      {
    
        char[] target = Arrays.copyOf( str, str.length );
    
        int index = 0;
        for ( int i = 0; i < target.length; i++ )
        {
          if ( str[ i ] == '-' )
          {
            target[ i ] = a[ index ];
            index++;
          }
        }
        return new BigInteger( new String( target ) );
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-07
      • 2020-12-21
      • 1970-01-01
      • 2013-04-14
      • 2018-04-14
      • 1970-01-01
      • 2017-06-06
      • 2020-01-07
      相关资源
      最近更新 更多