繁体   English   中英

java中如何用“+”替换一个字符?

[英]how to replace a character with “ + ” in java?

所以我正在尝试制作一个程序,该程序将以扩展形式写入一个数字(例如,当输入为 12 时,结果将为 10 + 2)

我使用递归来解决这个问题。 我想我有代码,它可以打印出实际数字,我需要做的就是返回一个字符串,在每个 0 和 [1-9] 整数之间带有一个“+”。 这样我就可以从“102”到“10 + 2”

问题是当我尝试

replaceAll("(0)([1-9])", "$1 + $2");

我遇到了一个无限递归问题,我无法确定为什么会发生这种情况。 但这不会发生在任何其他输入上。

例如,如果我要做

replaceAll("(0)([1-9])", "$1 - $2");

它会完美地工作。 它会返回“10 - 2”

甚至见鬼

replaceAll("(0)([1-9])", "$1 +  $2");

由于额外的空间,按预期工作并返回“10 + 2”

我不知道为什么唯一不起作用的输入是“$ 1 + $ 2”,有人请帮助我疯了。

public class Kata
{
    public static String expandedForm(int num)
    {
      int i = 0;
      int x = 0;
      int withZeros = 0;
      if (num <= 0) {
        return "";
      }
      
        for(i = String.valueOf(num).length() - 1; i >= 0; i--){
          x = Integer.parseInt(String.valueOf(String.valueOf(num).charAt(i)));
        
          if (x != 0) {
            break;
          }
        }
       
        
        if (i == String.valueOf(num).length() - 1) {
          withZeros = x;
        }
        else {
           withZeros = Integer.parseInt(String.valueOf(String.valueOf(num).charAt(i))) * 
              ((String.valueOf(num).length() - (i+1)) * 10);
            
        }
      
          
      String result = (expandedForm(num - withZeros) + withZeros).replaceAll("(0)([1-9])", "$1 + $2");
      
      
      
      
    
      return result;
    }
}

我看不出您的正则表达式替换方法会导致任何错误的任何原因。 考虑:

String input = "102";
String output = input.replaceAll("0([1-9])", "0 + $1");
System.out.println(output);  // 10 + 2

如果您的目标是将 int 转换为扩展形式,我建议使用简单的 for 循环而不是递归:

import java.lang.Math;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Main
{
    public static void main(String[] args) {
        int input = 102;
        System.out.println(expandedForm(102));  
    }
    
    public static String expandedForm(int num) {
        String str = String.valueOf(num);
        char[] ch = str.toCharArray();
        
        List<String> list = new ArrayList<>();
        
        for (int i = ch.length - 1, j = 0; i >= 0; i--, j++) {
            if(ch[i] != '0') {
                int n = Integer.valueOf(ch[i] - '0') * (int)Math.pow(10, j);
                list.add(String.valueOf(n));
            }
        }
        
        Collections.reverse(list);
        
        return String.join(" + ", list);
    }
}

在线GDB

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM