【HackerRank】 Sherlock and The Beast

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 }
复制代码

 

posted @   SunshineAtNoon  阅读(612)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示