如何編寫(xiě)可以用Java計(jì)算能力的函數(shù)。無(wú)循環(huán)
嘗試遞歸:
int pow(int base, int power){ if(power == 0) return 1; return base * pow(base, --power);}解決方法
我一直在嘗試用Java編寫(xiě)一個(gè)簡(jiǎn)單的函數(shù),該函數(shù)可以不使用循環(huán)就可以計(jì)算出n次方的數(shù)字。然后,我發(fā)現(xiàn) Math.pow(a,b) 類(lèi)…或方法仍然無(wú)法區(qū)分兩者,理論上不太好。所以我寫(xiě)了這個(gè)
public static void main(String[] args) { int a = 2; int b = 31; System.out.println(Math.pow(a,b)); }
然后,我想制作自己的 Math.pow 而不使用循環(huán),我希望它看起來(lái)比循環(huán)更簡(jiǎn)單,就像使用某種類(lèi)型的 Repeat一樣,我做了很多研究,直到遇到遇到使用 StringUtils.repeat 的 commons-lang3 包為止。 到目前為止,我認(rèn)為這是語(yǔ)法: __
public static String repeat(String str,int repeat) StringUtils.repeat('ab',2);
的 問(wèn)題 我已經(jīng)面臨的 過(guò)去24小時(shí) 或更多的是, StringUtils.repeat(字符串str,整數(shù)2);重復(fù)字符串,而不是推銷(xiāo),數(shù)字或計(jì)算。我可以做些什么來(lái)克服這個(gè)問(wèn)題,還是有其他更好的方法來(lái)創(chuàng)建一個(gè)計(jì)算冪的函數(shù)?不使用循環(huán)或Math.pow
這可能很有趣,但是花了我一段時(shí)間才弄清楚 StringUtils.repeat 只重復(fù)字符串,這就是我試圖克服它的方式。萬(wàn)一有幫助
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謝謝您的所有評(píng)論,即使存在語(yǔ)法錯(cuò)誤,只要能理解邏輯對(duì)我也有好處 :)
相關(guān)文章:
1. 數(shù)組按鍵值封裝!2. 關(guān)docker hub上有些鏡像的tag被標(biāo)記““This image has vulnerabilities””3. docker不顯示端口映射呢?4. Docker for Mac 創(chuàng)建的dnsmasq容器連不上/不工作的問(wèn)題5. java - 阿里的開(kāi)發(fā)手冊(cè)中為什么禁用map來(lái)作為查詢(xún)的接受類(lèi)?6. python3.x - git bash如何運(yùn)行.bat文件?7. python - flask _sqlalchemy 能否用中文作為索引條件8. dockerfile - 我用docker build的時(shí)候出現(xiàn)下邊問(wèn)題 麻煩幫我看一下9. nignx - docker內(nèi)nginx 80端口被占用10. android - 百度地圖加載完成監(jiān)聽(tīng)
