1.不通过第三个变量交换2个变量值
a = a+b;
b = a-b;
a = a-b;
2.打印正三角
for(int i = 1;i<=5;i++){
for(int j = 1;j<=i;j++){
System.out.print("*");
}
System.out.println();
}
3.打印倒三角
for(int i = 1;i<=5;i++){
for(int j = i;j<=5;j++){
System.out.print("*");
}
System.out.println();
}
4.十进制转十六进制
char[] arr = new char[8];
int index = arr.length - 1;
String str = "";
int temp;
while(num != 0){
temp = num & 15;
if(temp > 9){
arr[--index] = temp - 10 + 'A';
}else{
arr[--index] = (char)(temp - '0');
}
num = num >> 4;
}
for(int i = index ;i < arr.length;i++){
str += arr[i];
}
5.数组排序(选择、冒泡)
选择:
for(int i = 0;i < arr.length - 1;i++){
for(int j = i + 1; j < arr.length;j++){
if(arr[i]>arr[j]){
交换
}
}
}
冒泡:
for(int i = 0;i < arr.length - 1;i++){
for(int j = 0; j < arr.length-1-i;j++){
if(arr[i]>arr[j]){
交换
}
}
}
6.数组查找(普通、二分)
普通:
for(int i = 0;i<arr.length;i++){
if(arr[i] == key){
return i+1;
}
}
二分:
int min = 0;
int max = arr.length-1;
int mid = (min+max)/2;
while(key != arr[mid]){
if(key>arr[mid]){
min = mid + 1;
}else if{
max = mid - 1;
}
if(min > max)
return -1;
mid = (min+max)/2;
}