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);
    }
    
    
}
 
本文出自 “遁一” 博客

發佈留言