zoukankan      html  css  js  c++  java
  • 【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 }
  • 相关阅读:
    nyoj 42 一笔画 欧拉通路
    布丰投针实验1
    poj 1328 贪心
    uva 10026 贪心
    zoj 1375 贪心
    uva 103 经典DAG变形
    uva 11088 暴力枚举子集/状压dp
    jsp分页功能
    static静态变量的理解
    Vector & ArrayList 的主要区别
  • 原文地址:https://www.cnblogs.com/sunshineatnoon/p/3877513.html
Copyright © 2011-2022 走看看