当前位置:编程学习 > JAVA >>

Java面试题

求s=a+aa+aaa+aaaa+aa...a的值,其中a是一个数字。例如2+22+222+2222+22222(此时共有5个数相加 (a也可以是10,99,919等)
以下是Java类:
 
public class CalculateA {
    //所要求的计算表达式长度
    private int num;
    //a的值
    private int a;
 
    public CalculateA(int num, int a) {
        // TODO Auto-generated constructor stub
        this.num = num;
        this.a = 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;
 
    }
}
测试类:
 
import junit.framework.Assert;
 
import org.junit.Test;
 
public class CalculateATest {
 
    @Test
    public void testGetCalculatedResult() {
        //a是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);
    }
    
    
}
 
本文出自 “遁一” 博客

补充:软件开发 , Java ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,