1.不用中间变量,用两种方法交换A和B的值
// 1.中间变量
void swap(int a, int b) {
int temp = a;
a = b;
b = temp;
}
// 2.加法
void swap(int a, int b) {
a = a + b;
b = a - b;
a = a - b;
}
// 3.异或(相同为0,不同为1. 可以理解为不进位加法)
void swap(int a, int b) {
a = a ^ b;
b = a ^ b;
a = a ^ b;
}
2.求最大公约数
/** 1.直接遍历法 */
int maxCommonDivisor(int a, int b) {
int max = 0;
for (int i = 1; i <=b; i++) {
if (a % i == 0 && b % i == 0) {
max = i;
}
}
return max;
}
/** 2.辗转相除法 */
int maxCommonDivisor(int a, int b) {
int r;
while(a % b > 0) {
r = a % b;
a = b;
b = r;
}
return b;
}
// 扩展:最小公倍数 = (a * b)/最大公约数
3.不用内置函数求一个数的平方根
网上查到用二分法,牛顿迭代法,求极限等方法
float sqrt(int num) {
float mid=0f;
float left = 0f;
float right = num;
while(left <right) {
mid = (left+right)/2;
if(Math.abs(mid*mid -num)==0){
return mid;
} else if (mid*mid -num<0){
left=(mid+num)/2 ;
} else {
right=mid/2 ;
}
}
return mid;
}
4.用最有效率的方法计算2乘以8?
答: 2 << 3(左移3位相当于乘以2的3次方,右移3位相当于除以2的3次方)。
5.链表反序
public Entry reverse() {
Entry pre = null;
Entry cur = head;
Entry newHead = null;
while (cur != null) {
Entry curNext = cur.next;
if (curNext == null) {
newHead = cur;
}
cur.next = pre;
pre = cur;
cur = curNext;
}
return newHead;
}
例如:a->b->c
解析
第一次
cur=a;
curNext=b;
a.next=null;
pre=a;
cur=b;
第二次
cur=b;
curNext=c;
b.next=a;
pre=b;
cur=c;
第三次
cur=c;
curNext=null;
newHead=c;
c.next=b;
pre=c;
cur=null;
三次后变为:a<-b<-c
6.写个菜单树递归
private void buildSubs2(CategoryVO parent, List<CategoryVO> allList) {
List<CategoryVO> children = new ArrayList<>();
for (CategoryVO categoryVO : allList) {
if (categoryVO.getParentId() == parent.getPid()) {
children.add(categoryVO);
}
}
if (!CollectionUtils.isEmpty(children)) {
parent.setChildren(children);
for (CategoryVO categoryVO : children) {
buildSubs2(categoryVO, allList);
}
}
}
网友评论