如何編寫可以用Java計算能力的函數(shù)。無循環(huán)
嘗試遞歸:
int pow(int base, int power){ if(power == 0) return 1; return base * pow(base, --power);}解決方法
我一直在嘗試用Java編寫一個簡單的函數(shù),該函數(shù)可以不使用循環(huán)就可以計算出n次方的數(shù)字。然后,我發(fā)現(xiàn) Math.pow(a,b) 類…或方法仍然無法區(qū)分兩者,理論上不太好。所以我寫了這個
public static void main(String[] args) { int a = 2; int b = 31; System.out.println(Math.pow(a,b)); }
然后,我想制作自己的 Math.pow 而不使用循環(huán),我希望它看起來比循環(huán)更簡單,就像使用某種類型的 Repeat一樣,我做了很多研究,直到遇到遇到使用 StringUtils.repeat 的 commons-lang3 包為止。 到目前為止,我認為這是語法: __
public static String repeat(String str,int repeat) StringUtils.repeat('ab',2);
的 問題 我已經(jīng)面臨的 過去24小時 或更多的是, StringUtils.repeat(字符串str,整數(shù)2);重復(fù)字符串,而不是推銷,數(shù)字或計算。我可以做些什么來克服這個問題,還是有其他更好的方法來創(chuàng)建一個計算冪的函數(shù)?不使用循環(huán)或Math.pow
這可能很有趣,但是花了我一段時間才弄清楚 StringUtils.repeat 只重復(fù)字符串,這就是我試圖克服它的方式。萬一有幫助
public static int repeat(int cal,int repeat){ cal = 2+2; int result = StringUtils.repeat(cal,2); return result;}
我可以不使用遞歸,也許這樣的事情
public static RepeatThis(String a){ System.out.println(a); RepeatThis(a);}
只是試圖理解dept中的java謝謝您的所有評論,即使存在語法錯誤,只要能理解邏輯對我也有好處 :)
相關(guān)文章:
1. python文檔怎么查看?2. python - pycharm 自動刪除行尾空格3. 安全性測試 - nodejs中如何防m(xù)ySQL注入4. python - pandas按照列A和列B分組,將列C求平均數(shù),怎樣才能生成一個列A,B,C的dataframe5. python - Pycharm的Debug用不了6. html - eclipse 標簽錯誤7. python 利用subprocess庫調(diào)用mplayer時發(fā)生錯誤8. 請問PHPstudy中的數(shù)據(jù)庫如何創(chuàng)建索引9. datetime - Python如何獲取當前時間10. javascript - 有適合開發(fā)手機端Html5網(wǎng)頁小游戲的前端框架嗎?
