Java written test strong training Niuke.com selected programming questions 02

1. Choice

Single choice

Merge N ordered linked lists of length M. The merged linked lists will also remain ordered. The time complexity is ()?

  • A O(N * M * logN)
  • B O(N*M)
  • C O(N)
  • D O(M)

1. Create a max/min heap of length N. Take out the first elements of these N linked lists to create a minimum heap. Time complexity: O(N)

2. Take out the elements (top of the heap) from the minimum heap in sequence. At this time, the top of the heap is the minimum value of the current set, and put other elements of the linked list into the heap. The time complexity of adjusting the heap: O(siftDown - N*M*logN), the total number of elements that need to be added to the heap, O(N*M*logN)

3. Total: building a heap + constantly adjusting the heap (continuously taking out the top elements of the heap) O(N) + O(N*M*logN), taking the highest order: O(N*M*logN)

In a circular queue with a size of MAX, f is the current position of the head element, and r is the position of the current tail element (the position of the last element). Then at any time, the number of elements in the queue is

  • A r-f
  • B (r-f+MAX+1)%MAX
  • C r-f+1
  • D (r-f+MAX)%MAX

Insert image description here

The HASH function conflict handling method does not include any of the following:

  • A open addressing method
  • B chain address method
  • C insertion sort
  • D Public Overflow Area Act

It is known that the small root heap is 8,15,10,21,34,16,12. After deleting keyword 8, the heap needs to be rebuilt. During this process, the number of comparisons between keywords is ().

  • A 1
  • B 2
  • C 3
  • D 4

The top of the heap is exchanged with the last element of the heap, and adjusted downward to a small root heap.

Insert image description here

Among the following options, the one that cannot be the second sorting result of quick sort is ()

  • A 2,3,5,4,6,7,9
  • B 2,7,5,6,4,3,9
  • C 3,2,5,4,7,6,9
  • D 4,2,3,5,7,6,9

Every time a quick row is performed, the calibration point must be at the final position. After two quick queues, at least two elements reached the final position:

A:2 3 9。B:2 9。C:9。D:5 9

The average execution time complexity and required additional storage space complexity of heap sort are ()

  • AO(N2) sum O(1)
  • B O(Nlog2N) sum O(1)
  • CO(Nlog2N) and O(N)
  • DO(N2) sum O(N)

In-place heap sort

Which of the following statements about JVM memory is wrong?

  • A The program counter is a relatively small memory area, used to indicate which line of bytecode executed by the current thread has been executed, and is thread-isolated.
  • B Java method execution memory model is used to store local variables, operand stacks, dynamic links, method exits and other information, and is thread-isolated
  • The C method area is used to store data such as class information, constants, static variables, and code compiled by the just-in-time compiler loaded by the JVM. It is thread-isolated.
  • D In principle, all objects allocate memory in the heap area and are shared between threads.

The method area is shared by threads

The output result of the following program segment is: ( )

public void complicatedexpression_r(){
     
     
     int x=20, y=30;
     boolean b;
     b = x > 50 && y > 60 || x > 50 && y < -60 || x < -50 && y > 60 || x < -50 && y < -60;
     System.out.println(b);
 }
  • A true
  • Bfalse _
  • C 1
  • D 0

Input streams load data into memory from files, standard input, or other external input devices. In Java, they correspond to abstract classes () and their subclasses.

  • A java.io.InputStream
  • B java.io.OutputStream
  • C java.os.InputStream
  • D java.os.OutputStream

Which of the following statements about program compilation is correct ()

  • A Java language is a compiled language, which compiles Java programs into binary machine instructions and runs them directly.
  • B The target file compiled by java is related to the specific operating system.
  • C java translates instructions only at runtime
  • The target file compiled by D java can be run on any jvm

Java is a semi-compiled and semi-interpreted language

class is an operating system-independent, JVM-oriented binary file

1. Compile: javac, *.java -> *.class. 2. Run: javaJVM will actually translate the class file into machine code for system operation.

JVM also has versions. The class file JDK8 of JDK11 cannot run.

Which of the following situations can terminate the running of the current thread?

  • A When a high-priority thread enters the ready state
  • B throws an exception
  • C When the thread calls the sleep() method
  • D when creating a new thread

Termination of the thread:
1. The task of the thread is completed (normal termination)
2. An exception occurs during the execution of the thread (abnormal termination)

public static void main(String args[]) {
    
    
        Thread t=new Thread(){
    
    
            public void run(){
    
    
                dianping();
            }
        };
        t.run();
        System.out.print("dazhong"); }
    static void dianping(){
    
    
        System.out.print("dianping");
    }
  • A dazhongdianping
  • B dianpingdazhong
  • C a and b are both possible
  • D dianping loop output, dazhong is mixed in the middle

In this question, thread t has not been started, but the run() method has been called. Run() is called directly without starting a new thread. It is equivalent to calling an ordinary method. There is still only one thread running in the program, so the program will be executed in order, that is, run() will be run first, the run() method will call the dianping() method to output "dianping", and the program will continue to execute downwards and output "dazhong". If the t thread in this question calls the start() method, option C will appear. To sum up, the correct answer is B.

public interface IService {String NAME=“default”;}

Which item does the default type equivalent represent:

  • A public String NAME=“default”;
  • B public static String NAME=“default”;
  • C public static final String NAME=“default”;
  • D private String NAME=“default”;

The variables in the interface are all global constants public static final

There are following class definitions:

abstract class Animal{
     
     
 abstract void say();
}
public class Cat extends Animal{
     
     
 public Cat(){
     
     
     System.out.printf("I am a cat");
 }
 public static void main(String[] args) {
     
     
     Cat cat=new Cat();
 }
}

After running:

  • A I am a cat
  • B Animal can be compiled, but Cat cannot be compiled.
  • C Animal cannot be compiled, but Cat can be compiled.
  • D compilation can pass, but there is no output result

Subclasses of abstract classes must override all abstract methods (subclasses are not abstract classes)

In Java, which of the following descriptions about method overloading and method overriding is correct?

  • A method overloading and method overriding implement the same function
  • B method overloading appears in the parent-child relationship, and method overriding is in the same class
  • The return value type of C method overloading must be consistent, and the parameter items must be different
  • The return value types of D method overrides must be the same or compatible.
// 向上转型类的返回值可以
class A {
    
    
    A test() {
    
    
        return this;
	}
}

class B extends A {
    
    
    B test() {
    
    
		return this;s
    }
}

Which of the following statements about memory recycling are correct? ( )

  • A The programmer must create a thread to free the memory
  • B The memory recycling program is responsible for releasing useless memory **
  • C memory reclaimer allows programmers to free memory directly
  • D memory recycling program can release memory objects at a specified time

JVM garbage collection is performed by the JVM itself

Which of the following statements is correct:

  • A formal parameters can be modified by field modifiers
  • B formal parameters cannot be objects
  • C formal parameters are the parameters that are actually passed when the method is called.
  • D formal parameters can be treated as local variables

A: Field modifier: access rights public, etc. C: Actual parameter. D: Formal parameters can be treated as local variables

In Java 7, which of the following statements is correct:

  • A ConcurrentHashMap uses the synchronized keyword to ensure thread safety
  • B HashMap implements the Collection interface
  • C Arrays.asList method returns java.util.ArrayList object
  • D SimpleDateFormat objects are thread-unsafe

A: lock. B: The Collection interface is the top-level interface of linear tables, and HashMap implements the Map interface. C: List interface object

public static <T> List<T> asList(T... a) {
    
    
    return new ArrayList<>(a);
}

Regarding the following program segment, the correct statement is: ()

String s1="abc"+"def";//1
String s2=new String(s1);//2
if(s1.equals(s2))//3
System.out.println(".equals succeeded");//4
if(s1==s2)//5
System.out.println("==succeeded");//6
  • Line 4 and line 6 of A are not executed.
  • B Line 6 is executed, but Line 4 is not executed.
  • C Line 4 is executed, but Line 6 is not executed.
  • D Lines 4 and 6 will be executed

To compare string objects for equality, use equals to compare content, and use == to compare addresses.

The result of running the following code in command mode is ()

public class f{
     
     
	public static void main(String[] args){
     
     
		String foo1 = args[1];
		String foo2 = args[2];
		String foo3 = args[3];
	}
}

Command: java fabc

  • A program compilation error
  • B a b c
  • C program running error
  • D f

Compile command: javac source file name.java *.java -> *.class
Run command: java main class name Parameters to be passed (in args passed to main)
java fabc —— args{a, b, c} —— [0-2]

Which of the following statements is correct?

  • A This can be used in a class method to call the class method of this class.
  • B can call the class method of this class directly in the class method.
  • C. In a class method, only the class method of this class can be called.
  • D Instance methods must not be called from within class methods

A: this represents the current object reference, and static fields cannot be called. B: Static methods have no objects that can be used directly. CD: If an object is created in a class method, instance methods can still be called through the object

class Test {
    
    
	void func() {
    
    };
    static void test() {
    
    
		Test test = new Test();
        test.func();
    }
}

The following class descriptions are known:

public class Test{
     
     
	private float f=1.0f;
	int m=12;
	static int n=1;
	public static void main(String args[]){
     
     
		Test t=new Test();
	}
}

Which of the following uses are correct ()

  • A t.f = 1.0
  • B this.n
  • C Test.m
  • D Test.n

There is the following code:

class A{
     
     
	public A(String str){
     
     
	}
}
public class Test{
     
     
	public static void main(String[] args) {
     
     
		A classa=new A("he");
		A classb=new A("he");
		System.out.println(classa==classb);
	}
}

The output result is:

  • to false
  • B true
  • C error
  • D None of the above options are correct

== compares the addresses of two references. Classa and classb are both new, so the addresses must not be equal.

Which of the following is not part of the java class loading process?

  • A generates java.lang.Class object
  • B int type object member variables are assigned default values
  • C execute static block code
  • D class method analysis

B: Member variables will not be initialized, only static variables will be initialized. Executed when the object is generated, after class loading, and does not belong to the class loading process

Which of the following can create and start a thread in java ()

public class MyRunnable implements Runnable {
     
     
	public void run() {
     
     
		//some code here
	}
}
  • A new Runnable(MyRunnable).start()
  • B new Thread(MyRunnable).run()
  • C new Thread(new MyRunnable()).start()
  • D new MyRunnable().start()

The process of creating and starting a thread is: define thread->instantiate thread->start thread. There are two ways to define threads, one is to inherit the java.lang.Thread class, and the other is to implement the java.lang.Runnable interface. The difference between these two ways of instantiating threads is that if you inherit the Thread class, you can just create a new object directly. If it is a class that implements the Runnable interface, you need to use the Thread constructor: Thread(Runnable target) Thread(Runnable target, String name) Thread(ThreadGroup group, Runnable target) Thread(ThreadGroup group, Runnable target, String name) Thread(ThreadGroup group, Runnable target, String name, long stackSize) Therefore, there are errors in instantiating threads in the two options A and D. . The MyRunnable in new Runnable (MyRunnable) in option B has not been instantiated, which will cause the compilation to fail. This option is wrong regardless of whether run() or start() is called later.

If you want to listen to TCP port 9000, how should you create a socket on the server side?

  • A new Socket(“localhost”,9000);
  • B new ServerSocket(9000);
  • C new Socket(9000);

The server uses ServerSocket(int port), which defaults to a locally specified port number to listen to the TCP port.
The client uses Socket to connect to the server Socket(lP, port)

Which of the following class declarations is correct?

  • A abstract final class HI{}

  • B abstract private move(){}

  • C protected private number;

  • D public abstract class Car{}

The modifier of the java interface can be ()

  • A private
  • B protected
  • C final
  • D abstract

The title refers to the modifiers used directly on the interface definition. The interface permissions are all public.

The standard for jre to judge whether the program execution has ended is ()

  • A All foreground threads have been executed
  • B All background threads have been executed
  • C All threads have been executed
  • D has nothing to do with the above

JRE: Java Runtime Environment
JDK: Java Development Kit, including JRE
When the Java process considers that the program has been fully executed: all foreground threads (user threads) have been executed and
manually set as background threads: setDameon(true)
Generally, the threads we create are foreground threads . Background thread: JVM garbage collection thread

int i=5;
int s=(i++)+(++i)+(i–)+(–i);
s=( )//What is the value of s?

  • A 28
  • B 25
  • C 21
  • D 26
  • E 24
  • F 23

5 7 7 5

The following are not methods in the Object class:

  • A hashCode()
  • B finally()
  • C wait()
  • D toString()

finalize()It is a method of Object class, used to release thread resources.

Which of the following does not belong to the jdk1.6 garbage collector?

  • A Serial Collector
  • B parNew collector
  • C CMS collector
  • D G1 Collector

Versions after JDK7

The instanceof operator can be used to determine whether an object is:

  • A an instance of a class
  • B An instance of a class that implements the specified interface
  • C All correct
  • D an instance of a subclass

Which of the following is a statement for class instantiation?

  • A varName ClassName=new varName();
  • B ClassName varName=new ClassName(new ClassName);
  • C ClassName varName=ClassName();
  • D ClassName varName=new ClassName();

Class name reference name = new class();

When you compile and run the following code, which of the following options occurs?

public class Pvf{
     
     
	static boolean Paddy;
	public static void main(String args[]){
     
     
		System.out.println(Paddy);
	}
}
  • A compile time error
  • B compiles successfully and outputs false
  • C compiles successfully and outputs the result true
  • D compiles successfully and outputs null result

Variables declared in a class have a default initial value; variables declared in a method do not have a default initial value and must be initialized when defined, otherwise an error will occur when accessing the variable. In this question, Paddy is a static member variable, so it will get an initial value of false of boolean type.

Which of the following statements is correct?

  • A instance method can directly call the instance method of the super class
  • B instance method can directly call the class method of the super class
  • C instance methods can directly call instance methods of subclasses
  • D instance methods can directly call instance methods of this class

A: super(). B: Class name. C: subclass object

HashSet subclasses rely on the () method to distinguish duplicate elements.

  • A toString(),equals()
  • B clone(),equals()
  • C hashCode(),equals()
  • D getClass(),clone()

First call the object hashcode method to map the object to an array subscript, and then use equlas to determine whether the element contents are the same.

What happens when the following code is compiled and run?

public class TestDemo{
     
     
 private int count;
 public static void main(String[] args) {
     
     
     TestDemo test=new TestDemo(88);
     System.out.println(test.count);
 }
 TestDemo(int a) {
     
     
     count=a;
 }
}
  • A compiles and runs successfully, and the output result is 88
  • B compile-time error, the count variable is defined as a private variable
  • C compile-time error, test is not initialized when the System.out.println method is called
  • D There is no output when compiling and executing

private can be used inside the class, count is a member variable, accessed through the object

The result of executing the following program is:

class X{
     
     
 Y y=new Y();
 public X(){
     
     
     System.out.print("X");
 }
}
class Y{
     
     
 public Y(){
     
     
     System.out.print("Y");
 }
}
public class Z extends X{
     
     
 Y y=new Y();
 public Z(){
     
     
     System.out.print("Z");
 }
 public static void main(String[] args) {
     
     
     new Z();
 }
}
  • A ZYXX
  • B ZYXY
  • C YXYZ
  • D XYZX

Initialize static member variables and static code blocks in the parent class; Initialize static member variables and static code blocks in the subclass; 3. Initialize ordinary member variables and code blocks of the parent class, and then execute the construction method of the parent class; 4. Initialization Initialize the ordinary member variables and code blocks of the subclass, and then execute the construction method of the subclass; the specific process is as follows: (1) Initialize the ordinary member variables and code blocks of the parent class, execute Y y=new Y(); output Y (2) Then execute the construction method of the parent class; output C

  • When inheriting, first call the constructor of the parent class
  • The initialization operations of member variables in the class are all performed in the constructor method.

There is such a program:

public class Test{
     
     
 public String name="abc";
 public static void main(String[] args){
     
     
     Test test=new Test();
     Test testB=new Test();
     System.out.println(test.equals(testB)+","+test.name.equals(testB.name));
 }
}

What is the result of executing the above program ()

  • A true,true
  • B true,false
  • C false,true
  • D false,false

The equals method provided by Object defaults to comparing whether the object addresses are the same. Strings override the equals method to compare whether the values ​​are equal.

Consider the following simple example and let's see how reflection works.

import java.lang.reflect.*;
public class DumpMethods{
     
     
 public static void main(String[] args) {
     
     
     try {
     
     
         Class c=Class.forName(args[0]);
         Method m[]=c.getDeclaredMethods();
         for (int i = 0; i < m.length; i++) {
     
     
             System.out.println(m[i].toString());
         }
     } catch (Throwable e) {
     
     
         System.err.println(e);
     }
 }
}

The function of "c.getDeclaredMethods" is:

  • A Get the public method object of the class
  • B Gets the names of all public methods of the class
  • C Get all method objects of the class
  • D None of the above options are correct

Insert image description here

Java's character type uses the Unicode encoding scheme, and each Unicode code occupies () bits.
A 8
B 16
C 32
D 64

Which of the following multi-threaded operations on int type variable x does not require synchronization ()
A ++x
B x=y
C x++
D x=1

B: The assignment of x relies on a variable being non-atomic. D: Direct assignment operations are atomic operations

There are the following 4 statements: ()

Integer i01=59; // 自动装箱
int i02=59;
Integer i03=Integer.valueOf(59); // 装箱
Integer i04=new Integer(59); // 在堆上 new 了一个新对象

The following output results are false:
A System.out.println(i01==i02); // Automatically unbox i01 and restore it to an integer
B System.out.println(i01==i03); // true
C System.out.println(i03==i04); // If there is new, there will be new space, and the addresses of i03 and i04 are not equal
. System.out.println(i02==i04); // Automatically unboxing, i04 is restored to int

​ Options A and D, when the wrapper class is compared with the basic data type, the wrapper class will automatically unbox and become the basic type for comparison, that is, Integer i01 will be unboxed into the int type and compared with i02. Therefore System.out.println(i01==i02); output is true. Option B, the wrapped data class directly assigns value, and its corresponding valueOf() method is called by default. Then Integer i03=Integer.valueOf(59); is equivalent to Integer i01=59; valueOf() operates an integer within -128 ~ 127. When it is referenced for the first time, a new object will be created in the cache; when it is referenced again , search directly from the cache; if you operate an integer other than -128 ~ 127, you will need to create a new object every time. That is to say, if you have created an integer between -128 ~ 127, when you use valueOf to create it for the second time, the new keyword will not be used, but the cached object will be used. Therefore System.out.println(i01==i03); outputs true. Option C, the wrapper class is a reference type of the basic data type. The definition of i04 uses the new keyword, which will open up a new memory to place the Integer object with a value of 59. Then the result of == judgment for two reference type variables with different addresses is naturally false. Answer choice C.

// 原码:
public static Integer valueOf(int i) {
    
    
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }

In a uniprocessor system, if 12 processes exist at the same time, the maximum number of processes in the ready queue is ()

A 1

B 9

C 10

D 11

Which of the following statements about multithreading is incorrect:

  • A Thread synchronization methods include using critical sections, mutexes, semaphores, etc.
  • B Two threads also need to be mutually exclusive when writing to simple type global variables at the same time.
  • When implementing a reentrant function in C , mutexes must also be used to protect automatic variables.
  • D Reentrant functions cannot call non-reentrant functions

Critical section: Access public resources or a piece of code through serialization of multiple threads. It is fast and suitable for controlling data access. (The critical section can be thought of as a piece of code that operates shared resources)
Mutex: Designed to coordinate separate access to a shared resource. Semaphore: Designed for controlling a resource with a limited number of users. |
Event: used to notify the thread that some events have occurred, thereby starting the subsequent task

Reentrant function:
Mainly used in multi-tasking environments. A reentrant function is simply a function that can be interrupted. That is to say, the function can be interrupted at any time during its execution and transferred to OS scheduling for execution. Another piece of code, but no errors will occur when returning control;
non-reentrant functions:
Because some system resources are used, such as global variable areas, interrupt vector tables, etc., problems may occur if it is interrupted. This Class functions cannot run in a multi-tasking environment.
Automatic variable:
local scope variable, which is created when it is defined. When the function returns, the system reclaims the space; it is private to the thread.

Possible causes of system deadlock are

  • A process infinite loop
  • B resource loop waiting
  • C program memory access out of bounds
  • D process releases resources

Integer 0x12345678, the sorting sequence of memory in bigendian is ( )

  • A 12 34 56 78
  • B 78 56 34 12
  • C 87 65 43 21
  • D 21 43 65 87

bigendian big endian mode, littleenddian little endian mode

Using C to set a 1G byte character array all the way to word 'A' would take the closest order of magnitude of CPU time on a typical contemporary PC ()

  • A 0.001 seconds
  • B 1 second
  • C 100 seconds
  • D 2 hours

The conversion rules between units are:

1GB = 1024MB
1MB = 1024KB

1KB = 1024B

1B = 8bits
, so 1GB = 1,073,741,824B.
It takes about 1ns to execute a statement, which is 1/1,00o,000,000 seconds (10^9). Every time 1B is assigned, a statement must be executed, so for 1G, it is about 1 second. 10^9 * 1,073,741,824

For ordinary computers, the average time-consuming order of the following events from small to large is ____:

A. Read 1KB memory data B. Continuously read 1KB data from the hard disk C. Read the L2 cache once D. One disk seek

  • A C,A,D,B
  • B C,D,A,B
  • C D,C,A,B
  • D D,A,C,B

Cache is level 2 cache, which means secondary cache. Data interacts directly with the CPU through the cache. This is the fastest and most direct.

In the second memory reading time, when searching for data through the CPU cache, it is found that the data does not exist in the cache. At this time, it needs to be searched in the memory, but the transmission speed of the memory is not as fast as the cache, so the memory reading The time consumption of data is greater than caching.

The third one reads 1kb continuously from the hard disk, which means reading hard disk data. The time consumption of reading hard disk data is mainly composed of seek time , data transmission time , and rotation time , so the disk The seek time is definitely less than the total sequential read time.

In a paging virtual storage management system, the size of the page and the number of page fault interruptions that may occur ( )

  • A is directly proportional to
  • B is inversely proportional to
  • C irrelevant
  • D becomes a fixed value

Paged virtual storage system:
stores a copy of the job information (referring to the data information to be operated on in the memory) in auxiliary storage such as a disk. When a job is scheduled to run, all the program and data of the job are not loaded. Main memory, and only load those pages that are used immediately , at least the first page of the job information must be loaded into main memory , and when pages that are not in main memory are accessed during execution, they will be loaded dynamically.

The more commonly used paging virtual storage management is demand paging. When a certain instruction or data needs to be executed and it is found that they are not in the main memory, a page fault interrupt is generated and the system starts from the secondary memory. The page where the instruction or data is located is loaded into the memory.

The content of the page entered into the memory does not change . Therefore, in a paging virtual storage management system, the size of the page has little to do with the number of page fault interruptions that may occur.

Regarding child processes and parent processes, which of the following is correct? ()

  • A A parent process can create several child processes, and a child process can be subordinate to several parent processes.
  • When the parent process B is canceled, all its child processes are also canceled accordingly.
  • C When a child process is revoked, its dependent parent process is also revoked.
  • D A process can have no parent or child processes

A: A parent process can create multiple child processes, but a child process only belongs to one parent process.
B: If the parent process exits first and the child process has not exited, then the child process will be entrusted to the init process, and the child process will be entrusted to the init process. Complete status collection on them. At this time, the parent process of the child process is the init process ((Process No. 1). The init process has no parent process.
C: The child process exits, and the parent process can continue to execute
. D: The init process has no parent process; a process does not need to create a child process. process

Regarding threads and processes, the following statement is correct ()

  • A Terminating a process takes less time than terminating a thread
  • B Process switching takes less time than thread switching within the same process
  • C threads improve communication efficiency between different executors
  • D Processes and threads are the basic units of resource allocation and scheduling.

The creation, switching, termination, and time-consuming/consuming resources of processes are all higher than those of threads. Change AB to high, D is process

During process scheduling, which of the following process state changes is impossible to occur? ()

  • A blocking pending -> blocking
  • B ready pending -> ready
  • C ready pending -> blocking pending
  • D blocking suspension->ready suspension

Insert image description here

Operating system programs that are running should be placed in ()

  • in A register
  • B in main memory
  • C auxiliary storage

The running operating system program refers to the process, which is in the main memory.

Register: Limited capacity, only the data needed for the CPU to execute the code is loaded (loaded from main memory to register)

Auxiliary storage: When the process is suspended, the process will be saved in auxiliary storage.

The main purpose of setting up disk buffers in system memory is ().

  • A Reduce the number of disk I/O
  • B Reduce average seek time
  • C Improve disk data reliability
  • D Achieve device independence

Disk buffers have disks and disk buffers

The CPU execution speed is much faster than the disk IO speed.
In order to improve efficiency, disk cache can be used to increase the IO speed for frequently accessed disk data.

B does not reduce the seek time, but the number of

Among the following options, the event that will cause the process to change from execution state to ready state is ().

  • A performs P(wait) operation
  • B Failed to apply for memory
  • C Start I/O device
  • D is preempted by a high-priority process

A: One of the ways of process communication, signal: p (wait) semaphore -1, v (signal) semaphore +1. According to the semaphore, if it is a positive number, you can continue execution

B: The operating system kernel will notify the process, and the process will decide how to execute it. Generally, an error will be reported.

Which of the following statements is not a primary function of an operating system? ()

  • A Processor Management
  • B memory management
  • C Device management and file management
  • D portable

Processor Management: Process Management

The main purpose of using buffering technology in modern operating systems is ().

  • A Improve user programming environment
  • B Increase the processing speed of the CPU
  • C Increase the degree of parallelism between CPU and device
  • D Achieve device independence

The CPU execution speed is much faster than the disk IO speed, so a buffer is added in the middle. The CPU can read and write data to the buffer at the same time, and the disk can also read and write data to the buffer.

An essential difference between a process and a program is ().

  • A The former is dynamic and the latter is static
  • B The former is stored in memory and the latter is stored in external memory
  • C The former is in one file and the latter is in multiple files
  • D The former uses the CPU in a time-sharing manner, while the latter monopolizes the CPU

A program is a static executable file in external memory. If the process is running, it is in memory; if it is suspended, it is in external storage. D: The program is not running. It is a static executable file. The statement is wrong.

After a process's disk read operation is completed, what the operating system must do for the process is ()

  • A Modify the process status to ready state
  • B Reduce process priority
  • C. The process allocates user memory space
  • D Increase the time slice size of the process

The process io operation is blocking. After reading a section into the buffer, the operating system is notified to schedule the process from the blocking state to the ready state.

BCD has nothing to do with io operations

The algorithm that selects pages that have not been visited for a long time in the recent past for elimination is called ().

  • A Opt.
  • B LRU
  • C DEAD
  • LFU

OPT (Optimal page replacement algorithm)
is the best page replacement algorithm. It predicts which page will appear latest and replaces that page.

LRU (Least Recently Used)
least recently used page replacement algorithm, that is, the page that has not been used for the longest time is eliminated first.
MFU (Most Frequently Used)
most frequently used algorithm, replaces the most frequently used pages

LFU (Least Frequently Used) is
the least frequently used page replacement algorithm, which eliminates the pages that have been visited the least frequently within a certain period of time .

between concurrent processes().

  • A have nothing to do with each other
  • B must be synchronized
  • C must be mutually exclusive
  • D may require synchronization or mutual exclusion

Mutual exclusion:
refers to a number of program fragments walking among different tasks. When a task runs one of the program fragments, other tasks cannot run any of them and can only wait until the task finishes running this program fragment . The program fragment can be run only after it is created . The most basic scenario is: a public resource can only be used by one process or thread at a time, and multiple processes or threads cannot use public resources at the same time.

Synchronization:
refers to a number of program fragments walking between different tasks. Their operation must be run in strict accordance with a certain specified order. This order depends on the specific tasks to be completed . The most basic scenario is: two or more processes or thread pools coordinate and run in a predetermined order. For example, the operation of task A depends on the data produced by task B.
Obviously, synchronization is a more complex mutual exclusion, and mutual exclusion is a special kind of synchronization.

The end of an I/O operation may result in ().

  • A A process changes from sleep to ready
  • B Several processes changed from sleep to ready
  • C A process changes from sleeping to running
  • D Several processes changed from sleeping to running

If a user process reads data from a disk file through the read system call, which of the following descriptions about this process is correct ( ). Ⅰ. If the data of the file is not in the memory, the process enters sleep waiting state II. Requesting the read system call will cause the CPU to switch from user mode to kernel mode III. The argument to the read system call should contain the name of the file

  • A Only Ⅰ, Ⅱ
  • B Only Ⅰ, Ⅲ
  • C Only Ⅱ and Ⅲ
  • D Ⅰ, Ⅱ and Ⅲ

read is io reading, 1. The disk reads data to the memory, 2. The CPU obtains the data from the memory (fast),

Ⅰ. If the data of the file is not in the memory, the purpose of entering the sleep mode is to wait for the memory to map the file on the disk. Because the reading of the disk is slow, it enters the sleep mode.
Ⅱ. read is a system call, so the CPU switches from user mode to core mode.
Ⅲ. The open system call should contain the name of the file, and read only contains the input stream.

Linux file permissions are 10 digits long and divided into four sections. What does the third section represent ()?

  • A file type
  • B File owner’s permissions
  • C Permissions for the group that owns the file
  • D Permissions of other users

Insert image description here

Regarding the description of read-write lock, the following is correct ()

  • A At any time, there is only one thread that obtains the lock permission.
  • B A read-write lock can exist for readers and writers at the same time
  • C When the read-write lock is in the write-locked state, other threads performing write operations will not be blocked and will always loop to check whether the read-write lock is available.
  • D The read-write lock can be used for read sharing in the read-locked state.

When the write lock is locked, other threads can no longer perform read operations (apply for a read lock) or write operations (apply for a write lock), that is, write and write mutual exclusion, read and write mutual exclusion

When the read lock is locked, other threads can also perform read operations, that is, read-read concurrency.

Reasons for process blocking do not include ________.

  • A time slice switching
  • B Equal waiting I/O
  • C process sleep
  • D Waiting for unlocking

Analysis: The process has 3 states: ready state, executing state, and blocked state. The transitions between the three states include: ready->execution, execution->ready, execution->blocking, blocking->ready, waiting for I/O, process sleep, waiting for unlocking and other reasons will cause the process to pause. Regarding "time slice switching", when the process has obtained all resources except the CPU, the state at this time is the ready state. When the time slice is allocated, it becomes the execution state. When the time slice is used up, it does not enter the blocking state. , and then continue to enter the ready state. So process readiness and blocking are completely different.

During page fault processing, the operation performed by the operating system may be (). Ⅰ.Modify page table II. Disk I/O III. allocate page frame

  • A Only Ⅰ, Ⅱ
  • B only II
  • C only III
  • D Ⅰ, Ⅱ and Ⅲ

Page fault:
It is a concept after the introduction of virtual memory. After the operating system is started, a virtual address table is maintained in the memory, and the virtual addresses required by the process are recorded in the virtual address table. When a program is loaded and run, only a small part of it is loaded into memory, and the other part is loaded from disk when needed.
The part loaded into memory is marked as "resident", while the part not loaded into memory is marked as "non-resident". The operating system reads the virtual address table as needed. If the address recorded in the virtual address table is marked as "not resident", it means that the program code recorded in this part of the address has not been loaded into the memory and needs to be read from the disk. This situation means "missing page".

Page frame:
A circuit is added to the CPU that can automatically convert the virtual memory (ie logical address) address into a physical memory address. In order to simplify this circuit, the RAM is divided into blocks of 4KB or 8KB in length. This block is called Page frame.
The kernel uses page frames as the basic unit to manage physical memory. In the paging unit, a page refers to a group of data stored in the virtual memory of a process, and the physical memory that stores this group of data is the page frame. When this group of data is released, if If other processes request access to this memory, the pages in the page frame will change.


2. Programming questions

Year-end Award——Dynamic Planning

The company where Xiaodong works is going to issue a year-end bonus, and Xiaodong happens to get the highest benefit. He has to participate in a lottery game at the company's annual meeting. The game is played on a 6*6 chessboard, with 36 pieces of varying values ​​placed on it. Gift, there is a gift placed on each small chessboard. He needs to start the game from the upper left corner. He can only move one step down or to the right at a time and stop at the lower right corner. Xiaodong can get the gifts in the grids along the way. Come, please design an algorithm so that Xiaodong can get the gift with the highest value.

Given a 6*6 matrix board , each element is the gift value of the corresponding grid, and the upper left corner is [0,0]. Please return the maximum value that can be obtained, ensuring that the value of each gift is greater than 100 and less than 1000.

import java.util.*;

public class Bonus {
    
    
    public int getMost(int[][] board) {
    
    
        // write code here
        for (int i = 0; i < board.length; i++) {
    
    
            for (int j = 0; j < board[0].length; j++) {
    
    
                if (i == 0 && j == 0) {
    
    
                    continue;
                } else if (i == 0) {
    
     // 上面没有 最大值就是 加上前一个
                    board[i][j] += board[i][j - 1];
                } else if (j == 0) {
    
     // 左边没有 最大值就是 加上上一个
                    board[i][j] += board[i - 1][j];
                } else {
    
     // 加左一个和上一个的最大值
                    board[i][j] += Math.max(board[i][j - 1], board[i - 1][j]);
                }
            }
        }
        // 返回最后一个
        return board[board.length - 1][board[0].length - 1];
    }
}

Maze problem - recursion

Define a two-dimensional array N*M, as shown below for a 5 × 5 array:
int maze[5][5] = { 0, 1, 0, 0, 0, 0 , 1, 1, 1, 0, 0 , 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0, }; It represents a maze, where 1 represents the wall, 0 represents the path that can be taken, and only Walking sideways or vertically, not diagonally , requires programming to find the route from the upper left corner to the lower right corner. The entry point is [0,0], that is, the first grid is the way to go.






Data range: 2≤n,m≤10, the input content only contains 0≤val≤1

Enter description:

输入两个整数,分别表示二维数组的行数,列数。再输入相应的数组,其中的1表示墙壁,0表示可以走的路。数据保证有唯一解,不考虑有多解的情况,即迷宫只有一条通道。

Output description:

左上角到右下角的最短路径,格式如样例所示。

enter

5 5
0 1 0 0 0
0 1 1 1 0
0 0 0 0 0
0 1 1 1 0
0 0 0 1 0

output

(0,0)
(1,0)
(2,0)
(2,1)
(2,2)
(2,3)
(2,4)
(3,4)
(4,4)

[Problem-solving ideas]

Each location has four directions:
the direction you can go: no crossing the boundary, no obstacle, no walking before

Search:
Current position (x, y):
Determine whether (x, y) has crossed the boundary, whether (x, y) has been passed before, whether there are obstacles in (x, y). No crossing
, no passing, no obstacles:

  1. Save current location in path
  2. (x, y) is the lower right corner, the exit position: a new path is generated.
    Determine whether the new path is a shorter path. If it is a shorter path, update the path.
  3. Continue to search for (x, y) four directions
  4. Delete the current location from the path and find a new path
import java.util.*;

// 存放当前位置 (x, y)
class Node {
    
    
    int x;
    int y;

    public Node(int x, int y) {
    
    
        this.x = x;
        this.y = y;
    }
}

public class Main {
    
    
    public static void main(String[] args) {
    
    
        Scanner scanner = new Scanner(System.in);
        // 迷宫矩阵
        int row = scanner.nextInt();
        int col = scanner.nextInt();
        int[][] maze = new int[row][col];
        for (int i = 0; i < row; i++) {
    
    
            for (int j = 0; j < col; j++) {
    
    
                maze[i][j] = scanner.nextInt();
            }
        }
        // 搜索最短路径
        ArrayList<Node> path = new ArrayList<>();
        ArrayList<Node> minPath = new ArrayList<>();
        int[][] book = new int[row][col];
        getMinPath(maze, row, col ,0, 0, book, path, minPath);
        // 打印最短路径
        for (Node node : minPath) {
    
    
            System.out.println("(" + node.x + ","  + node.y + ")");
        }
    }

    /**
     * @param maze 迷宫矩阵
     * @param row col 行 列
     * @param x y 当前位置
     * @param book 标记当前矩阵,标记当前位置是否走过
     * @param path 保存当前路径的每一个位置
     * @param  minPath 记录最短路径
     */
    private static void getMinPath(int[][] maze, int row, int col, int x, int y, int[][] book, ArrayList<Node> path, ArrayList<Node> minPath) {
    
    
        // 1、判断 (x, y) 是否越界、走过、有障碍
        if (x < 0 || x >= row || y < 0 || y >= col
                || book[x][y] == 1 || maze[x][y] == 1) {
    
    
            return;
        }
        // 2、把当前位置 存入路径
        path.add(new Node(x, y));
        // 3、标记当前为位置
        book[x][y] = 1;
        // 4、判断当前位置是否为出口
        if (x == row - 1 && y == col - 1) {
    
    
            // 到出口,一条新的路径产生,判断是否要更新最短路径
            if (minPath.isEmpty() || path.size() < minPath.size()) {
    
    
                minPath.clear();
                for (Node node : path) {
    
    
                    minPath.add(node);
                }
            }
        }
        // 5、继续搜索以 (x, y) 的上下左右四个方向
        getMinPath(maze, row, col, x - 1, y, book, path, minPath);
        getMinPath(maze, row, col, x + 1, y, book, path, minPath);
        getMinPath(maze, row, col, x, y - 1, book, path, minPath);
        getMinPath(maze, row, col, x, y + 1, book, path, minPath);
        // 6、回退到当前位置,把当前位置,从路径中删除,寻找新的路径
        path.remove(path.size() - 1);
        book[x][y] = 0;
    }
}

several roots

Number roots can be found by adding up the digits in a number. If the result is a one-digit number, then this number is the root; if the result is a two-digit number or a number with more digits, then add the numbers. Continue in this way until you get a single digit.
For example, for 24, adding 2 and 4 gives 6. Since 6 is a single digit, 6 is the root of 24.
Another example is 39. Add 3 and 9 to get 12. Since 12 is not a single digit, you have to add 1 and 2, and finally you get 3. This is a single digit, so 3 is the root of 39.
Now you are given a positive integer and output its root.
Enter description:

输入包含多组数据。

每组数据数据包含一个正整数n(1≤n≤10E1000)。

Output description:

对应每一组数据,输出该正整数的数根。

enter

24
39

output

6
3

[Problem-solving ideas]

Find the tree root of a positive integer n. The range of n is [1,10^1000]. Both
int and long are not within the value range . To receive input data at this time, only the following types can be considered:

(1) BigDecimal
(2) String

The question requires adding each digit. Relatively speaking, it is easier to use String to traverse from 0 and then add.
Things to note:
(1) The result after addition may not be a single digit, that is, it does not satisfy the tree. The root requirement needs to be added again.
For example, 759, then it is 7+5+9=21, which is not a single digit. It needs to be calculated again: 2+1=3, then the root of the tree is 3.
(2) You can use charAt for strings The (int index) method obtains characters. The characters can be directly converted to int
special ones. When the characters are numbers 0-9, you can use the character and character subtraction operation to get the difference in numbers,
such as '9'- '6. The return value is the result 3 of 9-6.
So for the characters '0"-'9, to get the int value, use the character -"0', such as
the character '5'. To get the numerical value 5, use "5-0' That’s it

// write your code here
import java.util.*;

public class Main {
    
    
    public static void main(String[] args) {
    
    
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext()) {
    
    
            String n = scanner.nextLine(); // next
            while (n.length() > 1) {
    
     // 字符串 "10" --> len > 1 而不是 10
                int sum = 0;
                for (int i = 0; i < n.length(); i++) {
    
    
                    sum += n.charAt(i) - '0'; // 各位相加
                }
                n = String.valueOf(sum);
            }
            System.out.println(n);
        }
    }
}

interstellar code

After 100 years of interstellar war, NowCoder finally deciphered the alien code! Their password is a string of integers, mapped to a final 4-digit password through information in a table. The rules of the table are: the value corresponding to n is the upper left corner of the nth power of the matrix
|1 1|^n => |Xn …|
|1 0| |… …|
For example, when n=2,
|1 1|^2 => |1 1| * |1 1| => |2 1|
| 1 0| |1 0| |1 0| |1 1|
That is, the number corresponding to 2 is "0002".

Enter description:

输入有多组数据。
每组数据两行:第一行包含一个整数n (1≤n≤100);第二行包含n个正整数Xi (1≤Xi≤10000)

Output description:

对应每一组输入,输出一行相应的密码。

enter

6
18 15 21 13 25 27
5
1 10 100 1000 10000

output

418109877711037713937811
00010089410135017501

[Problem-solving ideas]

Prepare the Fibonacci data of f(xi) in advance.
Receive multiple groups of test cases
. Each group of test cases:
input the first line: integer n.
The second line: n numerical values ​​xi.
Output: calculate each xi, f(xi), all The result is concatenated into a string

Insert image description here

import java.util.*;

public class Main {
    
    
    public static void main(String[] args) {
    
    
        // 准备斐波那契数列
        int[] nums = new int[10001];
        nums[1] = 1; // 从 1 开始,对应
        nums[2] = 2;
        for (int i = 3; i < 10001; i++) {
    
    
            nums[i] = nums[i - 1] + nums[i - 2];
            nums[i] = nums[i] % 10000; // 如果大于4位的则只输出最后4位
        }
        // 多组测试用例
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNextInt()) {
    
    
            StringBuilder stringBuilder = new StringBuilder();
            int n = scanner.nextInt();
            for (int i = 0; i < n; i++) {
    
    
                int xi = scanner.nextInt();
                // 拼接每个 xi 的密码   格式化输出 如果这个数不足4位则用0填充
                stringBuilder.append(String.format("%04d", nums[xi]));
            }
            // 输出 n 个拼接的密码串
           System.out.println(stringBuilder.toString());
       }
    }
}

come into the bowl

Cats like to put themselves into containers (such as bowls), but if the circumference of the bowl is shorter than the cat's body length, they can't get in.

Now tell you their length and the radius of the bowl, please judge whether they can go into the bowl.

Enter description:

输入有多组数据。

每组数据包含两个整数n (1≤n≤2^128) 和r (1≤r≤2^128),分别代表喵的身长和碗的半径。

圆周率使用3.14。

Output description:

对应每一组数据,如果喵能装进碗里就输出“Yes”;否则输出“No”。

enter

6 1
7 1
9876543210 1234567890

output

Yes
No
No

1、double

import java.util.*;

public class Main {
    
    
    public static void main(String[] args) {
    
    
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext()) {
    
    
            double height = scanner.nextDouble();
            double r = scanner.nextDouble();
            if (2 * 3.14 * r < height) {
    
    
                System.out.println("No");
            } else {
    
    
                System.out.println("Yes");
            }
        }
    }
}

2、BigDecimal

Insert image description here

Note: import java.math.BigDecimal;

import java.util.*;
import java.math.BigDecimal;

public class Main {
    
    
    public static void main(String[] args) {
    
    
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext()) {
    
    
            BigDecimal n = scanner.nextBigDecimal();
            BigDecimal r = scanner.nextBigDecimal();
            BigDecimal len = new BigDecimal("6.28").multiply(r);
            // 身长 比 周长 长,进不去
            System.out.println(n.compareTo(len) == 1 ? "No" : "Yes");
        }
    }
}

Jumping step expansion problem

A frog can jump up one step at a time, or it can jump up two steps... It can also jump up n steps. Find out how many ways the frog can jump up an n-level step (n is a positive integer).

Data range: 1≤n≤20
Advanced: space complexity O(1), time complexity O(1)

Enter description:

本题输入仅一行,即一个整数 n 

Output description:

输出跳上 n 级台阶的跳法

enter

3

output

4

[Problem-solving ideas]

Insert image description here

public class Solution {
    
    
    public int jumpFloorII(int target) {
    
    
        return 1 << --target;
    }
}

Official recursion problem solution:

Regarding this question, the premise is that there will be an n-level jump for n steps. analyse as below:

f(1) = 1

f(2) = f(2-1) + f(2-2) //f(2-2) represents the number of times 2nd level jumps to 2nd level at a time.

f(3) = f(3-1) + f(3-2) + f(3-3)

f(n) = f(n-1) + f(n-2) + f(n-3) + … + f(n-(n-1)) + f(n-n)

illustrate:

1) f(n) here represents the number of n steps with one jump method of steps 1, 2,...n.

2) When n = 1, there is only one way to jump, f(1) = 1

3) When n = 2, there will be two ways to jump, 1st order or 2nd order at a time, which returns to problem (1), f(2) = f(2-1) + f(2-2)

4) When n = 3, there are three ways to jump, level 1, level 2, and level 3.

​ Then the first time you jump out of level 1, what’s left is: f(3-1); the first time you jump out of level 2, you’re left with f(3-2); the first time you jump out of level 3, then you’re left with f(3-3) )

​ Therefore the conclusion is f(3) = f(3-1)+f(3-2)+f(3-3)

5) n = n时,会有n中跳的方式,  1阶、2阶...n阶,得出结论: 

​ f(n) = f(n-1)+f(n-2)+…+f(n-(n-1)) + f(n-n) => f(0) + f(1) + f(2) + f(3) + … + f(n-1)

6) The above is already a conclusion, but for the sake of simplicity, we can continue to simplify:

​ f(n-1) = f(0) + f(1)+f(2)+f(3) + … + f((n-1)-1) = f(0) + f(1) + f(2) + f(3) + … + f(n-2)

​ f(n) = f(0) + f(1) + f(2) + f(3) + … + f(n-2) + f(n-1) = f(n-1) + f(n-1)

​ It can be concluded that:

​ f(n) = 2*f(n-1)

7) To draw the final conclusion, when there are steps 1, 2,...n at a time on n steps, the total jumping method is:

​ | 1 ,(n=0 )

f(n) = | 1 ,(n=1 )

​ | 2*f(n-1),(n>=2)

public class Solution {
    
    
    public int jumpFloorII(int target) {
    
    
        if (target <= 0) {
    
    
            return -1;
        } else if (target == 1) {
    
    
            return 1;
        } else {
    
    
            return 2 * jumpFloorII(target - 1);
        }
    }
}

triangle

Given three sides, please judge whether they can form a triangle.

Enter description:

输入包含多组数据,每组数据包含三个正整数a、b、c(1≤a, b, c≤10^100)。

Output description:

对应每一组数据,如果它们能组成一个三角形,则输出“Yes”;否则,输出“No”。

enter

1 2 3
2 2 2

output

No
Yes

1、double

import java.util.*;

public class Main {
    
    
    public static void main(String[] args) {
    
    
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNextDouble()) {
    
    
            double a = scanner.nextDouble();
            double b = scanner.nextDouble();
            double c = scanner.nextDouble();
            if ((a > (c - b)) && (a > (b - c)) && (b > (a - c))) {
    
    
                System.out.println("Yes");
            } else {
    
    
                System.out.println("No");
            }
        }
    }
}

2、BigDecimal

Insert image description here

import java.util.*;
import java.math.*;

public class Main {
    
    
    public static void main(String[] args) {
    
    
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext()) {
    
    
            BigDecimal a = scanner.nextBigDecimal();
            BigDecimal b = scanner.nextBigDecimal();
            BigDecimal c = scanner.nextBigDecimal();
            if (a.add(b).compareTo(c) > 0
               && a.add(c).compareTo(b) > 0
               && b.add(c).compareTo(a) > 0) {
    
    
                System.out.println("Yes");
            } else {
    
    
                System.out.println("No");
            }
        }
    }
}

The odd digits are all odd numbers or the even digits are all even numbers

import java.util.*;

public class Solution {
    
    
    public void oddInOddEvenInEven(int[] array) {
    
    
        int m = 0; // 偶数位
        int n = 1; // 奇数位
        while (m < array.length && n < array.length) {
    
    
            if (array[m] % 2 == 0) {
    
    
                m += 2;
                continue;
            }
            if (array[n] % 2 != 0) {
    
    
                n += 2;
                continue;
            }
            // 偶数位是奇数 奇数位是偶数 交换
            int tmp = array[m];
            array[m] = array[n];
            array[n] = tmp;
        }
    }
}

Monkey divides peaches

The old monkey worked hard all his life and left a huge fortune to the group of little monkeys - a lot of peaches. The old monkey decided to give these peaches to the little monkey.
The first monkey came and divided the peaches into five piles. The five piles had the same number, but there was one more. It left the remaining one to the old monkey and took a bunch of them himself.
The second monkey came and divided the peaches into five piles. The five piles had the same number, but there was one more. It left the extra one to the old monkey and took a bunch of them himself.
Later, the little monkeys followed suit. In the end, all the remaining peaches were left to the old monkey.
There are n little monkeys here. Please write a program to calculate at least how many peaches there are at the beginning, and at least how many peaches the old monkey can get at the end.
Enter description:

输入包括多组测试数据。
每组测试数据包括一个整数n(1≤n≤20)。
输入以0结束,该行不做处理。

Output description:

每组测试数据对应一行输出。
包括两个整数a,b。
分别代表开始时最小需要的桃子数,和结束后老猴子最少能得到的桃子数。

enter

5
1
0

output

3121 1025
1 1

[Problem-solving ideas]

// write your code here
import java.util.*;

public class Main {
    
    
    public static void main(String[] args) {
    
    
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext()) {
    
    
            int n = scanner.nextInt();
            if (n == 0) break;
            long a = (long) (Math.pow(5, n) - 4);
            long b = (long) (Math.pow(4, n) + n - 4);
            System.out.println(a + " " + b);
        }
    }
}

There are counterfeit coins

There are actually counterfeit coins! Now the price of pork has increased, but farmers’ wages have not. How can we buy pork if we don’t have money? nowcoder went to buy pork, but the change he got contained counterfeit coins! ! ! It's a pity that nowcoder accidentally mixed it into a pile of real coins. All you know is that the weight of the counterfeit currency is lighter than the mass of the real currency. Give you a scale (both ends of the scale can hold infinite coins), and please use the fastest time to find the abominable counterfeit currency.

Enter description:

1≤n≤2^30,输入0结束程序。

Output description:

最多要称几次一定能把那个假币找出来?

enter

3
12
0

output

1
3

[Problem-solving ideas]

The fastest way to find counterfeit currency in a pile of currency is to divide it into three piles and use two of the piles to weigh them.

Insert image description here

Counterfeit coins are lighter than real coins, so:
(1) If A<B, then the counterfeit coins are in A
(2) If A>B, then the counterfeit coins are in B
(3) If A=B, then the counterfeit coins are in C

Dividing a pile of currencies into three parts is the fastest way to find counterfeit currency.
The question asks how many times it needs to be weighed, so the worst case scenario is that the counterfeit currency is always in the three parts with the most.
For n currencies, n The range is [1, 2^30], divided into three parts each time, find the largest part, which is n/3 and round up.
If n=4, it is divided into 1, 1, 2, and the largest number is 2.
n=5, then it is divided into 2, 2, 1, and the largest number is 2.

Problem-solving idea:
Continuously cycle through n currencies, divide them into three parts each time, and take the largest part (n/3 is rounded up) until n=1 or n=2

Insert image description here

You can use Math.ceil()the method

Insert image description here

It should be noted that n/3 is int / int, the return value is also int, and the decimal has been lost. You
should use: (double)n/3 to return a floating point number, and then pass it as a parameter to Math.ceil()) method,
that is: Math. ceil((double)n/3)

import java.util.Scanner;

public class Main {
    
    
    public static void main(String[] args) {
    
    
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNextInt()) {
    
    
            int n = scanner.nextInt();
            if (n == 0) {
    
    
                break;
            }
            int count = 0;
            while (n >= 2) {
    
    
                n = (int) Math.ceil((double)n / 3);
                count++;
            }
            System.out.println(count);
        }
    }
}

Find the smallest unformable sum of an array of positive numbers - dynamic programming

Given an array arr that is all positive numbers, define the concept of the minimum unformable sum of arr: 1. Among all non-empty subsets of arr, adding up all the elements in each subset will result in many values, among which the smallest record is is min, and the largest one is recorded as max; 2. In the interval [min, max], if there are some positive numbers that cannot be obtained by adding a certain subset of arr, then the smallest one among these positive numbers is the minimum of arr The sum cannot be formed; 3. On the interval [min, max], if all numbers can be added by a certain subset of arr, then max+1 is the minimum unformable sum of arr; Example: arr = {3 ,2,5} The min of arr is 2 and the max is 10. On the interval [2,10], 4 is the smallest value that cannot be obtained by adding any subset, so 4 is the smallest unformable sum of arr. ; arr = {3,2,4} The min of arr is 2 and the max is 9. In the interval [2,9], 8 is the smallest value that cannot be obtained by adding any subset, so 8 is arr The minimum unformable sum of The smallest uncomposable sum of arr; Please write a function to return the smallest uncomposable sum of arr.

[Problem-solving ideas]

arr = {3,2,5} subset and the sum of the subsets are

  • {3}=3

  • {2}=2

  • {5}=5

  • {3.2}=5

  • {3,5}=8

  • {2,5}=7

  • {3.2.5}=10

The minimum sum of subsets is 2, the maximum sum of subsets is 10
in the range [2,10], and the minimum impossible sum of subsets is 4

Let j represent the sum of possible subsets of arr, which is any value in the range [2,10], and f() represents whether it is possible.
For example:

  • f(2) = true
  • f(3) = true
  • f(4) = false

Insert image description here

Insert image description here

Insert image description here

public class Solution {
    
    
	/**
	 *	正数数组中的最小不可组成和
	 *	输入:正数数组arr
	 *	返回:正数数组中的最小不可组成和
	 */
	public int getFirstUnFormedNum(int[] arr) {
    
    
        int min = Integer.MAX_VALUE;
        int max = 0;
        for (int i : arr) {
    
    
            min = Math.min(min, i);
            max += i;
        }
        boolean[] result = new boolean[max + 1];
        result[0] = true;
        for (int o : arr) {
    
     // 遍历数组元素
            for (int j = max; j >= o; j--) {
    
     // 遍历 max-min 向后往前到 o
                result[j] = result[j - o] || result[j]; // 本身就是
            }
        }
        for (int j = min; j < result.length; j++) {
    
     // result 中为 false 的就是不可组成
            if (!result[j]) {
    
    
                return j;
            }
        }
        return max + 1;
	}
}

hardest question

NowCoder lives in an era full of danger and conspiracy. To survive, he invented the first cipher for use in military messaging. Suppose you are an officer in the army and need to decipher the message sent and provide it
to your general.
The method of message encryption is to replace each letter in the original message with the fifth letter after that letter (for example: each letter A in the original message is replaced with the letter F), and other characters remain unchanged. And all letters of the original message are in capital letters. The correspondence between the letters in the password and the letters in the original text is as follows.
Password letters: ABCDEFGHIJKLMNOPQRSTU VWXYZ
Original letters: VWXYZABCDEFGHIJKLMNOP QRSTU
Input description:

输入包括多组数据,每组数据一行,为收到的密文。
密文仅有空格和大写字母组成。

Output description:

对应每一组数据,输出解密后的明文。

enter

HELLO WORLD<br/>SNHJ

output

CZGGJ RJMGY<br/>NICE
import java.util.*;

public class Main {
    
    
    public static void main(String[] args) {
    
    
        Scanner scanner = new Scanner(System.in);
        String letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        while (scanner.hasNextLine()) {
    
    
            String s = scanner.nextLine();
            StringBuilder stringBuilder = new StringBuilder();
            for (int i = 0; i < s.length(); i++) {
    
    
                if (Character.isLetter(s.charAt(i))) {
    
    
                    int index = letters.indexOf(s.charAt(i)); // 在字母串中的位置
                    index = (index - 5 + 26) % 26; // 前 5 个 字母 ABCDE 对应后面 TUVWX
                    stringBuilder.append(letters.charAt(index));
                } else {
    
     // 非字母 不需要转
                    stringBuilder.append(s.charAt(i));
                }
            }
            System.out.println(stringBuilder.toString());
        }
    }
}

Character conversion operations:
(1) int and char can be converted to each other, such as:
System.out.println((int)'A'); // 65
System.out.println((char)68); // D
(2 ) The subtraction of two uppercase letters must be equal to the subtraction after conversion to int. In this case, the following conclusion can be drawn:
System.out.println((char) ('A' + 2)); // C
System.out .println((char)('D' + 3)); // G
(3) If the added value cannot exceed the value of 'Z', otherwise it will become other characters

If it is not a space, it is an uppercase letter. If it is after 'E', it will be spliced ​​into the current character -5.
If it is 'A'-'E", it will be spliced ​​into the current character +21.

Insert image description here

import java.util.*;

public class Main {
    
    
    public static void main(String[] args) {
    
    
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNextLine()) {
    
    
            String s = scanner.nextLine();
            StringBuilder stringBuilder = new StringBuilder();
            for (int i = 0; i < s.length(); i++) {
    
    
                char c = s.charAt(i);
                if (c == ' ') {
    
    
                    stringBuilder.append(" ");
                } else {
    
    
                    stringBuilder.append((char) (c > 'E' ? c - 5 : c + 21));
                }
            }
            System.out.println(stringBuilder.toString());
        }
    }
}

Number of factors

A positive integer can be decomposed into the product of one or more arrays. For example, 36=2 2 3*3, which includes two factors: 2 and 3. NowCoder has recently been studying the distribution pattern of the number of factors. Now given a series of positive integers, he wants you to develop a program to output the number of factors for each positive integer.

Enter description:

输入包括多组数据。
每组数据仅有一个整数n (2≤n≤100000)。

Output description:

对应每个整数,输出其因子个数,每个结果占一行。

enter

30<br/>26<br/>20

output

3<br/>2<br/>2

How to find the fastest factor of n? If there is the following relationship:
n = x * y
If x<=y, then x must be in the range of [2, root n]
. That is to say, in [2, root n] No. n], the factors of n must be found

import java.util.*;

public class Main {
    
    
    public static void main(String[] args) {
    
    
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNextInt()) {
    
    
            int n = scanner.nextInt();
            int count = 0;
            for (int i = 2; i <= Math.sqrt(n); i++) {
    
    
                if (n % i == 0) {
    
    
                    while (n % i == 0) {
    
    
                        n /= i;
                    }
                    count++; // 因子的个数
                }
            }
            if (n != 1) {
    
     // 素数 再加一
                count++;
            }
            System.out.println(count);
        }
    }
}

decomposition factor

The so-called factorization is to decompose a given positive integer a into the product of several prime numbers, that is, a = a1 × a2 × a3 × … × an, and 1 < a1 ≤ a2 ≤ a3 ≤ … ≤ an. Among them, a1, a2,..., an are all prime numbers. First give an integer a, please output the decomposed factors.

Enter description:

输入包含多组数据,每组数据包含一个正整数a(2≤a≤1000000)。

Output description:

对应每组数据,以“a = a1 * a2 * a3...”的形式输出因式分解后的结果。

enter

10<br/>18

output

10 = 2 * 5<br/>18 = 2 * 3 * 3
import java.util.*;

public class Main {
    
    
    private static void AllFactors(int n, List<Integer> factors) {
    
    
        // 注意等于 10-> 2 * 5 变成5时 如果是小于 退出循环 只有 2
        for (int i = 2; i <= n; i++) {
    
    
            if (n == 0) {
    
    
                return;
            }
            while (n != 0 && n % i == 0) {
    
    
                factors.add(i);
                n /= i;
            }
        }
    }
    
    public static void main(String[] args) {
    
    
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNextInt()) {
    
    
            int n = scanner.nextInt();
            List<Integer> factors = new ArrayList<>();
            AllFactors(n, factors);
            System.out.print(n + " = ");
            for (int i = 0; i < factors.size() - 1; i++) {
    
    
                System.out.print(factors.get(i) + " * ");
            }
            System.out.println(factors.get(factors.size() - 1));
        }
    }
}
import java.util.*;

public class Main {
    
    
    private static List<String> factorization(int a) {
    
    
        List<String> ans = new ArrayList<>();
        for (int i = 2; a > 1 && i * i <= a; i++) {
    
    
            while (a % i == 0) {
    
    
                ans.add(String.valueOf(i));
                a /= i;
            }
        }
        if (a > 1) {
    
    
            ans.add(String.valueOf(a));
        }
        return ans;
    }
    
    public static void main(String[] args) {
    
    
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNextInt()) {
    
    
            int a = scanner.nextInt();
            List<String> factors = factorization(a);
            System.out.printf("%d = %s\n", a, String.join(" * ", factors));
        }
    }
}

american holiday

Unlike Chinese holidays, American holidays are usually based on the day of the week of a certain month, so the holiday dates are different every year. The specific rules are as follows:
* January 1: New Year's Day
* The third Monday in January: Martin Luther King Jr. Day
* The third Monday in February: President's Day
* The last Monday in May: Memorial Day
* July 4th: Fourth of July: Labor Day
* First Monday in September: Labor Day
* Fourth Thursday in November: Thanksgiving
* December 25th: Christmas
Now given a year, please You help generate the dates of the festivals of that year.
Enter description:

输入包含多组数据,每组数据包含一个正整数year(2000≤year≤9999)。

Output description:

对应每一组数据,以“YYYY-MM-DD”格式输出当年所有的节日日期,每个日期占一行。

每组数据之后输出一个空行作为分隔。

enter

2014
2013

output

2014-01-01
2014-01-20
2014-02-17
2014-05-26
2014-07-04
2014-09-01
2014-11-27
2014-12-25

2013-01-01
2013-01-21
2013-02-18
2013-05-27
2013-07-04
2013-09-02
2013-11-28
2013-12-25

【Analysis】

Question 1: Given ymd, how to know what day of the week the day is?

Taking December 31, 1 BC as the base value, this day is Sunday 7

The week of week(ymd):
the interval days % 7, plus the base week, it may be week 7, so then %7,

Interval number of days:
(ymd) - (0000-12-31) = the total number of days in the year + the number of days in the last year
                                   ~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~                                  = (y - 1)* 365+How many leap years have passed in the middle* 1+The number of days in the last year

[1,y) In all years, how many are divisible by 4: round down ((y - 1)/4) and (y - 1)/4 is rounded down and divisible by 100: (
y -1)/100 is divisible by 400: (y - 1) / 400
(y - 1) / 4 - (y - 1) / 100 + (y - 1) / 400 = the total number of leap years experienced

                                     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~                                     = 365* (y - 1) + (y- 1) / 4 - (y- 1) / 100 + (y - 1) / 400 + number of days in the last year

Simplify: 365 = 364 +1, 364 = 52*7, so 365 can be removed

Number of days in the last year: elapsed full month + day + leap year? 1 : 0

Question 2: It is known that the 1st of month m is weekday w. What day is it?

  • Given the day of the week January 1st, find the third Monday in January:

Insert image description here

  • Third Monday in February : Same as above
  • Given the day of the week September 1st, find the first Monday in September:

Assume it is Monday, September 1st: the answer is 1, which can be written as 1 + 0 * 7 + (7 - w + 1) % 7

Comparing the above formula, the month starts in January, so it is n - 1. If we find the third Monday, it is 3-1=2, which is 1 + (n - 1) * 7 + (7 - w + 1) % 7 is 1 + (1 - 1) * 7 + (7 - w + 1) % 7

  • The fourth Thursday in November:

1 + (n - 1) * 7 + (7 - w + 4) % 7 can be replaced by 4, which is 1 + (4 - 1) * 7 + (7 - w + 4) % 7

  • official:

f(w, n, e) = 1 + (n - 1) * 7 + (7 - w + e) ​​% 7 w
: the day of the week on the 1st of this month, n: find the number of this month, e: find the day of the week Several

  • Last Monday in May:

Insert image description here

Code:

import java.util.*;

public class Main {
    
    
    private static boolean isLeapYeat(int y) {
    
    
        return (y % 400 == 0) || (y % 4 == 0 && y % 100 != 0);
    }

    private static final int[] DAYS = {
    
    31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

    // 给定 y,m,d, 返回间隔天数
    private static int nDays(int y, int m, int d) {
    
    
        int n = d;
        for (int i = 0; i < m - 1; i++) {
    
    
            n += DAYS[i];
        }
        if (m > 2 && isLeapYeat(y)) {
    
    
            n++;
        }
        return n;
    }

    // 传入 y,m,d, 找到从公元前1年 12月31日开始过了多久。求它 MOD 7 的同余数
    private static int diff(int y, int m, int d) {
    
    
        return (y - 1) + (y - 1) / 4 - (y - 1) / 100 + (y - 1) / 400 + nDays(y, m, d);
    }

    // 根据 y,m,d, 求出星期几
    private static int week(int y, int m, int d) {
    
    
        int w = diff(y, m, d) % 7;
        if (w == 0) {
    
    
            w = 7;
        }
        return w;
    }

    // 根据 1 日的星期 w, 求第 n 个星期 e 是几号
    private static int m1(int w, int n, int e) {
    
    
        return 1 + (n - 1) * 7 + (7 - w + e) % 7;
    }

    // 根据 6月1日星期 w, 求 5月最后一个星期一
    private static int m2(int w) {
    
    
        int d = (w == 1 ? 7 : w - 1);
        return 32 - d;
    }

    public static void main(String[] args) {
    
    
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNextInt()) {
    
    
            int y = scanner.nextInt();

            System.out.printf("%d-01-01\n", y);

            int w = week(y, 1, 1);
            System.out.printf("%d-01-%02d\n", y, m1(w, 3, 1));

            w = week(y, 2, 1);
            System.out.printf("%d-02-%02d\n", y, m1(w, 3, 1));

            w = week(y, 6, 1);
            System.out.printf("%d-05-%02d\n", y, m2(w));

            System.out.printf("%d-07-04\n", y);

            w = week(y, 9, 1);
            System.out.printf("%d-09-%02d\n", y, m1(w, 1, 1));

            w = week(y, 11, 1);
            System.out.printf("%d-11-%02d\n", y,  m1(y, 4, 4));

            System.out.printf("%d-12-25\n", y);

            System.out.println();
        }
    }
}

Taobao store

NowCoder opened an online store on Taobao. He found that when the month is a prime number, he can earn 1 yuan per day in that month; otherwise, he can earn 2 yuan per day.
Now give you a period of time, please help him calculate the total income.

Enter description:

输入包含多组数据。

每组数据包含两个日期from和to (2000-01-01 ≤ from ≤ to ≤ 2999-12-31)。

日期用三个正整数表示,用空格隔开:year month day。

Output description:

对应每一组数据,输出在给定的日期范围(包含开始和结束日期)内能赚多少钱。

enter

2000 1 1 2000 1 31
2000 2 1 2000 2 29

output

62
29
import java.util.Scanner;

public class Main {
    
    
    private static boolean isPrimeNum(int n) {
    
    
        if (n == 1) {
    
     // 有 1 单独返回
            return false;
        }
        for (int i = 2; i < n; i++) {
    
    
            if (n % i == 0) {
    
    
                return false;
            }
        }
        return true;
    }

    private static boolean isLeap(int y) {
    
    
        if (y % 4 == 0 && y % 100 != 0 || y % 400 == 0) {
    
    
            return true;
        }
        return false;
    }

    private static int income(int fromYear, int fromMonth, int fromDay, int toYear, int toMonth, int toDay) {
    
    
        int income = 0;
        int[] monthDays = {
    
    31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

        if (isLeap(fromYear)) {
    
     // 起始年 是闰年
            monthDays[1] = 29;
        }
        // 1、同一年 单独计算
        if (fromYear == toYear) {
    
    
            // fromMonth - toMonth-1
            for (int i = fromMonth; i < toMonth; i++) {
    
    
                if (isPrimeNum(i)) {
    
    
                    income += monthDays[i - 1];
                } else {
    
    
                    income += monthDays[i - 1] * 2;
                }
            }
            // 只有一个月 fromDay - toDay
            income += isPrimeNum(fromMonth) ? toDay - fromDay + 1: (toDay - fromDay + 1) * 2;
            return income;
        }

        // 计算起始年 fromMont - 12 的收益
        if (isPrimeNum(fromMonth)) {
    
     // fromMonth 可能不是从第一天开始
            income += monthDays[fromMonth - 1] - fromDay + 1;
        } else {
    
    
            income += (monthDays[fromMonth - 1] - fromDay + 1) * 2;
        }
        for (int i = fromMonth + 1; i <= 12; i++) {
    
     // fromMonth - 12
            if (isPrimeNum(i)) {
    
    
                income += monthDays[i - 1];
            } else {
    
    
                income += monthDays[i - 1] * 2;
            }
        }
        // 结束年不是闰年 改回 28
        if (!isLeap(toYear)) {
    
    
            monthDays[1] = 28;
        }
        // 计算结束年 1 - toMonth-1 的收益
        for (int i = 1; i < toMonth; i++) {
    
     // 结束年 月
            if (isPrimeNum(i)) {
    
    
                income += monthDays[i - 1];
            } else {
    
    
                income += monthDays[i - 1] * 2;
            }
        }
        // toMonth 的 toDay 收益
        income += isPrimeNum(toMonth) ? toDay : toDay * 2; // 结束年 日
        // 2、相隔一年 返回
        if (fromYear + 1 == toYear) {
    
    
            return income;
        }

        // 3、相隔多年 加中间年
        monthDays[1] = 28; // 改回 28
        // 2000 - 2002    ---> 2001-2001 需要取等于
        for (int i = fromYear + 1; i <= toYear - 1; i++) {
    
    
            if (isLeap(i)) {
    
    
                monthDays[1] = 29;
            } else {
    
    
                monthDays[1] = 28;
            }
            for (int j = 1; j <= 12; j++) {
    
    
                if (isPrimeNum(j)) {
    
    
                    income += monthDays[j - 1];
                } else {
    
    
                    income += monthDays[j - 1] * 2;
                }
            }
        }
        return income;
    }

    public static void main(String[] args) {
    
    
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNextInt()) {
    
    
            // 2000 1 1 2999 12 31    579243
            int fromYear = scanner.nextInt();
            int fromMonth = scanner.nextInt();
            int fromDay = scanner.nextInt();
            int toYear = scanner.nextInt();
            int toMonth = scanner.nextInt();
            int toDay = scanner.nextInt();
            int income = income(fromYear, fromMonth, fromDay, toYear, toMonth, toDay);
            System.out.println(income);
        }
    }
}
import java.util.Scanner;

public class Main {
    
    
    private static boolean isLeap(int y) {
    
    
        return (y % 4 == 0 && y % 100 != 0 || y % 400 == 0);
    }

    // 给定一年 整年的收益
    private static int annualIncome(int year) {
    
    
        return 2 * 31
                + 28
                + 31
                + 2 * 30
                + 31
                + 2 * 30
                + 31
                + 2 * 31
                + 2 * 30
                + 2 * 31
                + 30
                + 2 * 31
                + (isLeap(year) ? 1 : 0);
    }

    private static boolean isPrime(int month) {
    
    
        return month == 2 || month == 3 || month ==  5 || month == 7 || month == 11;
    }

    // 从一年1月1日 到这一年 m,d 的收益
    private static int profitThisYear(int year, int month, int day) {
    
    
        int profit = 0;
        if (!isPrime(month)) {
    
    
            profit = day * 2;
        } else {
    
    
            profit = day;
        }

        while (--month > 0) {
    
    
            switch(month) {
    
    
                case 1: case 8: case 10: case 12:
                    profit += 62;
                    break;
                case 3: case 5: case 7:
                    profit += 31;
                    break;
                case 4: case 6: case 9:
                    profit += 60;
                    break;
                case 11:
                    profit += 30;
                    break;
                default: // 2 月
                    profit += (28 + (isLeap(year) ? 1 : 0));
                    break;
            }
        }
        return profit;
    }

    public static void main(String[] args) {
    
    
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNextInt()) {
    
    
            int fromYear = scanner.nextInt();
            int fromMonth = scanner.nextInt();
            int fromDay = scanner.nextInt();
            int toYear = scanner.nextInt();
            int toMonth = scanner.nextInt();
            int toDay = scanner.nextInt();

            int profit = 0;
            // 起始年:整年 - 到fromDay之间 (注意减一)
            profit = annualIncome(fromYear) - profitThisYear(fromYear, fromMonth, fromDay - 1);
            // 同一年 2000 5 17 2000 7 1
            // —> 5.17到12.31的收益 - 全年
            // = 负的一月一号到5.16的收益 + 加后面结束年
            // = 负的一月一号到5.16的收益 + 一月一号到7.1
            // = 5.17 - 7.1 的收益
            if (fromYear == toYear) {
    
    
                profit -= annualIncome(fromYear);
            }
            // 结束年
            profit += profitThisYear(toYear, toMonth, toDay);
            // 中间年
            for (int i = fromYear + 1; i < toYear; i++) {
    
    
                profit += annualIncome(i);
            }
            System.out.println(profit);
        }
    }
}

Fibonacci Phoenix Tail

NowCoder claims to have memorized all Fibonacci numbers between 1 and 100,000.
In order to test him, we randomly gave him a number n and asked him to tell the nth Fibonacci number. Of course, the Fibonacci numbers will be very large. Therefore, if the nth Fibonacci number has less than 6 digits, say that number; otherwise, only say the last 6 digits.

Enter description:

输入有多组数据。
每组数据一行,包含一个整数n (1≤n≤100000)。

Output description:

对应每一组输入,输出第n个斐波那契数的最后6位。

enter

1<br/>2<br/>3<br/>4<br/>100000

output

1<br/>2<br/>3<br/>5<br/>537501
// write your code here
import java.util.*;

public class Main {
    
    
    public static void main(String[] args) {
    
    
        int border = -1;
        int[] array = new int[100000];
        array[0] = 1;
        array[1] = 2;
        for (int i = 2; i < 100000; i++) {
    
    
            array[i] = array[i - 1] + array[i - 2];
            if (border == -1 && array[i] >= 1000000) {
    
     // 超过6位数 记录
                border = i + 1;
            }
            array[i] %= 1000000; // 用 border,后取模
        }
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNextInt()) {
    
    
            int n = scanner.nextInt();
            if (n < border) {
    
    
            System.out.printf(array[n - 1]);
            } else {
    
    
                System.out.printf("%06d\n", array[n - 1]);
            }   
        }
    }
    
    public static void main1(String[] args) {
    
    
        // 提前计算
        int[] array = new int[100000];
        array[0] = 1;
        array[1] = 2;
        for (int i = 2; i < 100000; i++) {
    
    
            array[i] = (array[i - 1] + array[i - 2]) % 1000000;
        }
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNextInt()) {
    
    
            int n = scanner.nextInt();
            // 补 0
            System.out.printf(n < 25 ? "%d\n" : "%06d\n", array[n - 1]);
        }
    }
}

Guess you like

Origin blog.csdn.net/qq_56884023/article/details/124936927
Recommended