Groovy 方法将二进制数转换为十进制数
我试着写一个程序,将二进制数转换成十进制数,但是出现了很多错误,我无法找出哪里出了问题Groovy 方法将二进制数转换为十进制数,groovy,binary,Groovy,Binary,我试着写一个程序,将二进制数转换成十进制数,但是出现了很多错误,我无法找出哪里出了问题 // Takes exponent from the user and calculates 2 ** exponent int power2(int exponent) { result = 2 ** exponent return result } // Converts binary number to decimal int binary2decimal(String binary)
// Takes exponent from the user and calculates 2 ** exponent
int power2(int exponent) {
result = 2 ** exponent
return result
}
// Converts binary number to decimal
int binary2decimal(String binary) {
result = 0
count = 0
for (i = binary.length(); i-- > 0;) {
int d = Integer.parseInt(binary.charAt(i))
if (d == 1) {
result = result + power2(count)
}
count ++
}
return result
}
binary2decimal("101110")
假设您希望获得清洁溶液的最短路径,请使用:
Integer.parseInt(字符串base2num,int基数)
,其中radix=2
请参见更改
int d = Integer.parseInt(binary.charAt(i))
到
它会起作用的
您的另一个实现是:
int binary2decimal2(String binary) {
binary.reverse()
.toList()
.indexed()
.collect { Integer idx, String val -> Integer.parseInt(val) * (2 ** idx)}.sum()
}
您是希望将算法开发为一个挑战,还是希望使用可用的方法?它是将算法开发为一个挑战。假设我们不知道可用的方法。谢谢,但出于本练习的目的,假设我们不知道/不能使用这些方法,并且必须构建一个类似于我发布的算法。谢谢,我使用了第一个解决方案来更改我的算法。但是,请您准确地解释一下“${binary[i]}”方法(我假设它取i处的位置值)。但是为什么不能使用.charAt方法将字符解析为整数?
charAt
返回一个char
parseInt
接受一个字符串
“${binary[i]}”
是一个字符串
int binary2decimal2(String binary) {
binary.reverse()
.toList()
.indexed()
.collect { Integer idx, String val -> Integer.parseInt(val) * (2 ** idx)}.sum()
}