1, 非遞歸實現 scala
/** * 把輸入的二進制數字轉換成十進制返回(非遞歸實現) * @param src 例如: "1111" * @return */ def binaryToDecWithOutRecur(src: String): Int = { if(!src.matches("[0|1]*")){ println("invalid input") return 0 } val tmp = src.reverse var res: Int = 0 for(i <- 0 to tmp.length - 1){ res += tmp.substring(i,i+1).toInt * (1 << i) } res }
2, 遞歸實現(線性遞歸) code
/** * 遞歸實現二進制串轉換成十進制數據輸出 * @param src * @return */ def binaryToDecRecur(src: String): Int = { if(!src.matches("[0|1]*")){ println("invalid input") return 0 } src.length match { case 0 => 0 case 1 => src.toInt * Math.pow(2,0).toInt case _ => binaryToDecRecur(src.substring(1,src.length)) + src.substring(0,1).toInt * (i << src.length - 1) } }
3, 遞歸實現(尾遞歸) 遞歸
/** * 遞歸實現二進制串轉換成十進制數據輸出(尾遞歸) * @param src * @param res * @return */ def binaryToDecTailRecur(src: String, res: Int): Int = { if(!src.matches("[0|1]*")){ println("invalid input") return 0 } src.length match { case 0|1 => res case _ => binaryToDecTailRecur(src.substring(0,src.length-1), res + src.substring(0,1).toInt * (1 << src.length - 1)) } } println(binaryToDecTailRecur("111110", 0))