日记式之java算法九九与水仙花小进阶(2018.12.7)

九九乘法表:

public class NNChange {
	public void finish(int number) {
		for(int i=1;i<=number;i++) {
			for(int j=1;j<=i;j++) {
				System.out.print(i+"*"+j+"="+i*j+" ");
			}
			System.out.println();
		}
	}
	public static void main(String[] args) {
		NNChange test = new NNChange();
		test.finish(9);
	}
}

水仙花:数字的各个位数的3阶等于它本身:例如370(3* 3 * 3+7 * 7* 7+0* 0*0=370),主要是%取余数与/取除数的应用。

public class Narcissus {
	/**
	 * 一位水仙花数
	 */
	public void oneNumber() {
		boolean bool = false;
		for(int i=1;i<=9;i++) {
			if(i*i*i==i) {
				System.out.println("一位数为:"+i);
				bool = true;
			}
		}
		if(bool==false) {
			System.out.println("二位数无水仙花数");
		}
	}
	/**
	 * 二位水仙花数
	 */
	public void twoNumber() {
		boolean bool = false;
		for(int i=10;i<=99;i++) {
			int a =i/10;
			int b =i%10; 
			if((a*a*a+b*b*b)==i) {
				System.out.print("二位数为:"+i+" ");
				bool = true;
			}
		}
		if(bool==false) {
			System.out.println("二位数无水仙花数");
		}
	}
	/**
	 * 三位水仙花数
	 */
	public void threeNumber() {
		boolean bool = false;
		for(int i=100;i<=999;i++) {
			int a =i/100;
			int b=i%100/10;
			int c=i%10;
			if((a*a*a+b*b*b+c*c*c)==i) {
				System.out.print("三位数为:"+i+" ");
				bool = true;
			}
		}
		System.out.println();
		if(bool==false) {
			System.out.println("三位数无水仙花数");
		}
	}
	/**
	 * 四位水仙花数
	 */
	public void fourNumber() {
		boolean bool = false;
		for(int i=1000;i<=9999;i++) {
			int a = i/1000;
			int b = i%1000/100;
			int c = i%100/10;
			int d = i%10;
			if((a*a*a+b*b*b+c*c*c+d*d*d)==i) {
				System.out.print("四位数为:"+i+" ");
				bool = true;
			}
		}
		if(bool==false) {
			System.out.println("四位数无水仙花数");
		}
	}
	public static void main(String[] args) {
		Narcissus test = new Narcissus();
		test.oneNumber();
		test.twoNumber();
		test.threeNumber();
		test.fourNumber();
	}
}

猜你喜欢

转载自blog.csdn.net/qq_38335295/article/details/84870062