java用递归将数字转换字符串,转换二进制数字字符串的十进制数...使用递归

Comp sci professor gave us this problem in our homework... I'm not sure how to proceed and the code I have written seems to be failing miserably. Here is the prompt:

(binary to decimal) Write a recursive method that parses a binary number as a string into a decimal integer. The method header is:

public static String bin2Dec(String binaryString)

write a test program that prompts the user to enter a binary string and displays its decimal equivalent.

Any help greatly appreciated. Here is my code as follows:

import java.util.Scanner;

public class HW04_P5 {

static int index = 0;

static int power = 0;

static int number = 0;

static boolean exit = false;

@SuppressWarnings("resource")

public static void main(String[] args){

Scanner scan = new Scanner(System.in);

System.out.print(" Enter a binary number to convert to decimal: ");

String in = scan.nextLine();

index = in.length()-1;

System.out.print(" Binary number converted to decimal: "+bin2Dec(in));

}

public static String bin2Dec(String in)

{

if((in.substring(index,index+1).equals("1"))&&(index>0))

{

number += Math.pow(2,power);

System.out.print(number);

power++;

index--;

bin2Dec(in);

}

else if((in.substring(index,index+1).equals("0"))&&(index>0))

{

power++;

index--;

bin2Dec(in);

}

System.out.print(number);

return "";

}

}

解决方案

It's cleaner not to have the extra variables index, power, and p. Just process the string from right to left. You also don't want the "global" variable number tracked outside the recursive function ... it's confusing and weird. You want all the state carried inside the recursive functions, in my opinion. Even with those restrictions, you can still do it in essentially two lines:

public static int bin2Dec(String s) {

if (s == null || s.isEmpty()) return 0;

else return s.charAt(s.length()-1)-48+2*bin2Dec(s.substring(0,s.length()-1));

}

That may not be the clearest solution, but it is the most elegant, I think. Clarity could be improved by breaking the else clause into several lines. 48 is the Unicode character number for 0, which is maybe not the best way to convert the characters '0' and '1' to their respective numbers.

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值