特定字符输出字符,如下所示:
input num :=2
output:as follow
layer 1
*
layer 2
*
***
input num :=4
output:as follow
layer 1
*
layer 2
*
***
layer 3
*
***
*****
layer 4
*
***
*****
*******
package com.java.interview.t_20140813;
import java.awt.DisplayMode;
import java.util.Scanner;
/**
* name: Test_Show.java
*
* date:2014-8-13 19:25:37
*
* function: output the special signals
*
* copyright: open
*
* @author wangxin
*
*/
public class Test_Show {
public static void main(String[] args) {
while (true) {
System.out
.println("Please input the num that you want to get! (< 0 to end)");
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
if (num <= 0) {
System.out.println("Error input, end the program!");
break;
} else {
// show(num);
display(num);
}
}
}
private static void display(int num) {
for (int i = 0; i < num; i++) {
System.out.println("layer " + (i + 1));
show(i + 1);
}
}
private static void show(int num) {
for (int i = 0; i < num; i++) {
show_blank(num - i - 1);
show_singal(i + 1);
show_blank(num - i - 1);
System.out.println();
}
}
private static void show_singal(int num) {
for (int i = 0; i < 2 * num - 1; i++) {
System.out.print("*");
}
// System.out.println();
}
private static void show_blank(int num) {
for (int i = 0; i < num; i++) {
System.out.print(" ");
}
}
}
二分法查找给定元素的位置<升序default>:
递归:
private static int binarySearch(List<Integer> list, int key, int low,
int high) {
if (low > high)
return -1;
int mid = (low + high) / 2;
if (list.get(mid) == key) {
return mid;
} else if (list.get(mid) < key) {
return binarySearch(list, key, mid + 1, high);
} else {
return binarySearch(list, key, low, mid - 1);
}
}
非递归:
public static int binary_Search(int[] array, int value) {
int low = 0;
int high = array.length - 1;
while (low <= high) {
int middle = (low + high) / 2;
if (value == array[middle]) {
return middle;
}
if (value > array[middle]) {
low = middle + 1;
}
if (value < array[middle]) {
high = middle - 1;
}
}
return -1;
}
用Python实现二分查找