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
#include<iostream> | |
#include<vector> | |
#include<algorithm> | |
using namespace std; | |
int main() | |
{ | |
int n; | |
while(cin >> n) | |
{ | |
int b=9; | |
string ans=""; | |
if(n==0) | |
{ | |
cout << 0 << endl; | |
continue; | |
} | |
else if(n==1) | |
{ | |
cout << 1 << endl; | |
continue; | |
} | |
while(b>1 && n>1) | |
{ | |
if(n%b==0) | |
{ | |
ans+=(b+'0'); | |
n/=b; | |
} | |
else | |
{ | |
b--; | |
} | |
} | |
vector<char> v; | |
for(int i=0; i<(int)ans.length(); i++) | |
{ | |
v.push_back(ans[i]); | |
} | |
sort(v.begin(), v.end()); | |
ans=""; | |
for(int i=0; i<(int)v.size(); i++) | |
{ | |
ans+=v[i]; | |
} | |
if(ans=="" || n>1) | |
{ | |
cout << -1 << endl; | |
} | |
else | |
{ | |
cout << ans << endl; | |
} | |
} | |
return 0; | |
} |
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
import java.util.*; | |
public class Main { | |
public static void main(String[] args) { | |
Scanner scn = new Scanner(System.in); | |
int n=scn.nextInt(); | |
while(n--!=0){ | |
int num=scn.nextInt(),i=9,tot=1,temp=num; | |
StringBuilder str=new StringBuilder(""); | |
if(num==1){ | |
System.out.println("1"); | |
continue; | |
}else if(num==0){ | |
System.out.println("0"); | |
continue; | |
} | |
while(i!=1){ | |
if(num%i==0){ | |
str.append(i); | |
tot*=i; | |
num/=i; | |
}else{ | |
i--; | |
} | |
} | |
if(temp==tot) | |
System.out.println(str.reverse()); | |
else | |
System.out.println("-1"); | |
} | |
} | |
/*題目:Q993: Product of digits | |
作者:1010 | |
時間:西元 2017 年 3 月 28日*/ | |
} |
這題其實不難,我當初想太複雜還用質數求公因數,但其實不是這樣的,題目只是要每個位數相乘等於你輸入的數目
舉例:90=>2*5*9 所以輸出259就好啦~很簡單吧
至於我是怎麼實作的,首先建立一個StringBuilder他類似於String型態但她可以呼叫reverse()字串翻轉很方便,那我們就從9開始除囉直到不等於1,若能整除依序append()到字串變數中,最後輸出reverse()就是最小數啦,那還要檢查最後如果每個位數相乘不等於輸入的數就輸出-1囉!
還有還有0跟1要個別判斷哦
沒有留言:
張貼留言