码迷,mamicode.com
首页 > 其他好文 > 详细

【HackerRank】 Sherlock and The Beast

时间:2014-07-30 12:00:53      阅读:412      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   http   color   java   os   strong   

Sherlock and The Beast

Sherlock Holmes is getting paranoid about Professor Moriarty, his archenemy. All his efforts to subdue Moriarty have been in vain. These days Sherlock is working on a problem with Dr. Watson. Watson mentioned that the CIA has been facing weird problems with their supercomputer, ‘The Beast‘, recently.

This afternoon, Sherlock received a note from Moriarty, saying that he has infected ‘The Beast‘ with a virus. Moreover, the note had the number N printed on it. After doing some calculations, Sherlock figured out that the key to remove the virus is the largest ‘Decent‘ Number having N digits.

A ‘Decent‘ Number has -
1. Only 3 and 5 as its digits.
2. Number of times 3 appears is divisible by 5.
3. Number of times 5 appears is divisible by 3.

Meanwhile, the counter to destruction of ‘The Beast‘ is running very fast. Can you save ‘The Beast‘, and find the key before Sherlock?

Input Format
The 1st line will contain an integer T, the number of test cases, followed by T lines, each line containing an integer N i.e. the number of digits in the number

Output Format
Largest Decent number having N digits. If no such number exists, tell Sherlock that he is wrong and print ‘-1‘

Constraints
1<=T<=20
1<=N<=100000


 

题解:

Java的String真是坑死爹啊,每次加入一个新的字符都要用O(N)的时间,所以如果不停的加入字符要用StringBuffer或者StringBuilder,要不就一直TLE。

代码如下:

 1 import java.io.*;
 2 import java.util.*;
 3 
 4 
 5 public class Solution {
 6 
 7     public static void main(String[] args) {
 8         Scanner in = new Scanner(System.in);
 9         int t = in.nextInt();
10         for(int i =0;i<t;i++){
11             int n = in.nextInt();
12             StringBuffer answer = new StringBuffer();
13             for(int j = 0;j <= n/5;j++){
14                 if((n-5*j)%3 == 0){
15                     for(int k = 0;k< n-5*j;k++)
16                         answer.append("5");
17                     for(int k = 0;k < 5*j;k++)
18                         answer.append("3");
19                     System.out.println(answer.toString());
20                     break;
21                 }
22             }
23             if(answer.toString().equals(""))
24                 System.out.println(-1);
25         }        
26     }
27     
28     
29     
30 }

 

【HackerRank】 Sherlock and The Beast,布布扣,bubuko.com

【HackerRank】 Sherlock and The Beast

标签:des   style   blog   http   color   java   os   strong   

原文地址:http://www.cnblogs.com/sunshineatnoon/p/3877513.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!