Java interview questions

Source: Internet
Author: User

Evaluate the value of s = a + aa + aaa + aaaa + aa... a, where a is a number. For example, 2 + 22 + 222 + 2222 + 22222 (at this time, there are 5 numbers added (a can also be 10, 99, 919, etc)
The following are Java classes:
 
Public class CalculateA {
// Required length of the calculated expression
Private int num;
// The value of
Private int;
 
Public CalculateA (int num, int ){
// TODO Auto-generated constructor stub
This. num = num;
This. a =;
}
 
Public long getCalculatedResult (){
Long result = 0L;
Int length = String. valueOf (a). length ();
 
Double repeate = Math. pow (10, length );
 
Int I = 0;
Int k = 1;
While (I <= num-1 ){
Result + = (num-I) * a * k;
I ++;
K * = repeate;
}
Return result;
 
}
}
Test class:
 
Import junit. framework. Assert;
 
Import org. junit. Test;
 
Public class CalculateATest {
 
@ Test
Public void testGetCalculatedResult (){
// When a is 0
CalculateA calculate = new CalculateA (5, 0 );
Assert. assertEquals (calculate. getCalculatedResult (), 0 );

// 0 <a <= 9
Calculate = new CalculateA (2, 1 );
Assert. assertEquals (calculate. getCalculatedResult (), 12 );

// A> 9
Calculate = new CalculateA (3, 10 );
Assert. assertEquals (calculate. getCalculatedResult (), 102030 );
}


}
 
This article is from the "yi" blog

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.