close
題目概要:
輸入2個數字n,m,判斷n是否為m的x次方,如果是請印出n,...,m^3,m^2 ,1(Ex n=125,m=5 印出125 25 5 1)。反之印出Boring!。
解題方向:
1. 數字超過int範圍,故需要使用long。
2. 從1開始乘上m,並記錄每次的結果,直到等於或超過n。
3. 如果Vector裡面是空的,或者最後一位數不等於n,則為Boring,反之就印出題目所需要的結果。
程式碼:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Java | |
import java.util.Scanner; | |
import java.util.Stack; | |
import java.util.Iterator; | |
class uva10190{ | |
public static void main(String args[]){ | |
Scanner sc=new Scanner(System.in); | |
while(sc.hasNextInt()){ | |
long n=sc.nextLong(); | |
long m=sc.nextLong(); | |
// Stack因為繼承於Vector,所以Vector的功能也可以使用。 | |
Stack<Long> stack=new Stack<Long>(); // Ps也可以使用一般陣列紀錄。 | |
long temp=1; | |
/* | |
1. m!=0 : 乘數不為零 | |
2. m!=1 : 乘數為1,不管乘上甚麼永遠都是1。 | |
3. n>=m : 因為m^x=n,所以n一定大於等於m。 | |
4. temp<=n : temp會越乘越大,當超過或等於n時即可停止迴圈。 | |
*/ | |
while(m!=0 && m!=1 && n>=m && temp<=n){ | |
stack.push(temp); | |
temp=temp*m; | |
} | |
//Output | |
Iterator<Long> it=stack.iterator(); | |
if(!stack.empty() && stack.lastElement()==n){ | |
while(true){ | |
long Stemp=stack.pop(); | |
System.out.print(Stemp); | |
if(Stemp!=1) System.out.print(" "); | |
else break; | |
} | |
System.out.println(""); | |
}else{ | |
System.out.println("Boring!"); | |
} | |
} | |
} | |
} |
文章標籤
全站熱搜