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 }
  • 相关阅读:
    JS浏览器兼容问题
    jsN位字母数字混合验证码
    js将数字变成数组
    JS跟随鼠标移动的提示框
    Grand Central Dispatch(GCD)编程基础
    C#学习之修饰符
    .NET 开源项目介绍及资源推荐:单元测试
    万般皆LINQ
    .NET 开源项目介绍及资源推荐:IOC容器篇
    Type.GetType(string typeName) returns null !?
  • 原文地址:https://www.cnblogs.com/sunshineatnoon/p/3877513.html
Copyright © 2011-2022 走看看