日期:2014-05-20  浏览次数:20628 次

在线等! 如何用递归法实现!
把一个十进制数的二进制表示中的连续的三位用另外三位换?(替换的三位与被替换的可以是任意的三位)
比如   1345的二进制是   10101000001   用111换101   则变为11101000001

要用递归实现!谢谢

------解决方案--------------------
转换为二进制串,然后用 String.replaceAll() 替换,然后转换回数字型。

--
http://www.agui.googlepages.com
mailto: agui.cn(a)gmail.com
------解决方案--------------------
楼上的。。。。LZ说要用递归 ···
------解决方案--------------------
public class JReplace {

/**
* @param args
*/
public static void main(String[] args) {
String basisStr= "10101010000101 ";
jReplace(basisStr, "101 ", "111 ", " ",0);
}
public static void jReplace(String basisStr,String otherStr,String replaceStr,String prefix,int index){

if(basisStr.length()-index <otherStr.length()){
System.out.println(basisStr);
}
else {
if(basisStr.regionMatches(index, otherStr, 0, otherStr.length())){
prefix=prefix+replaceStr;
index=index+otherStr.length();
}
else {
prefix=prefix+basisStr.charAt(index);
index=index+1;
}
basisStr=prefix+basisStr.substring(index,basisStr.length());
jReplace(basisStr,otherStr,replaceStr,prefix,index);
}
}
}