如何編寫可以用Java計算能力的函數。無循環
嘗試遞歸:
int pow(int base, int power){ if(power == 0) return 1; return base * pow(base, --power);}解決方法
我一直在嘗試用Java編寫一個簡單的函數,該函數可以不使用循環就可以計算出n次方的數字。然后,我發現 Math.pow(a,b) 類…或方法仍然無法區分兩者,理論上不太好。所以我寫了這個
public static void main(String[] args) { int a = 2; int b = 31; System.out.println(Math.pow(a,b)); }
然后,我想制作自己的 Math.pow 而不使用循環,我希望它看起來比循環更簡單,就像使用某種類型的 Repeat一樣,我做了很多研究,直到遇到遇到使用 StringUtils.repeat 的 commons-lang3 包為止。 到目前為止,我認為這是語法: __
public static String repeat(String str,int repeat) StringUtils.repeat('ab',2);
的 問題 我已經面臨的 過去24小時 或更多的是, StringUtils.repeat(字符串str,整數2);重復字符串,而不是推銷,數字或計算。我可以做些什么來克服這個問題,還是有其他更好的方法來創建一個計算冪的函數?不使用循環或Math.pow
這可能很有趣,但是花了我一段時間才弄清楚 StringUtils.repeat 只重復字符串,這就是我試圖克服它的方式。萬一有幫助
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謝謝您的所有評論,即使存在語法錯誤,只要能理解邏輯對我也有好處 :)
相關文章:
1. docker網絡端口映射,沒有方便點的操作方法么?2. docker images顯示的鏡像過多,狗眼被亮瞎了,怎么辦?3. docker start -a dockername 老是卡住,什么情況?4. docker gitlab 如何git clone?5. css3 - flex現在的兼容性如何6. javascript - 在bower.json中只有 bootstrap的信息并沒又其依賴的jquery。7. javascript - HTML 原生js怎么控制table根據0,1值來顯示或者隱藏8. dockerfile - [docker build image失敗- npm install]9. docker不顯示端口映射呢?10. docker-compose 為何找不到配置文件?
