剑指offer[16、18]

本文探讨了两个面试题:如何实现数值的整数次方功能,以及如何在链表中删除指定节点。对于数值次方,提供了求解方法;对于链表删除,解释了删除节点的操作流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

面试题16 数值的整数次方

题目:

实现函数double Power(double base, int exponent),求base的exponent次方。不得使用库函数,同时不需要考虑大数问题。

解法:

class Solution {
    public double myPow(double x, int n) {
        if(x==0) return 0;
        double res=1;
        //Java 代码中 int32 变量 n \in [-2147483648, 2147483647]n∈[−2147483648,2147483647] ,
        //因此当 n = -2147483648n=−2147483648 时执行 n = -nn=−n 会因越界而赋值出错。
        //解决方法是先将 nn 存入 long 变量 bb ,后面用 bb 操作即可。
        long b=n;
        if(b<0){
            x=1/x;
            b=-b;
        }
        while(b>0){
            if(b%2==1){
                res=res*x;
            }
            x=x*x;
            b=b/2;
        }
        return res;
    }
}
class Solution:
    def myPow(self, x: float, n: int) -> float:
        if not x: return 0
        res=1
        if n<0:
            x=1/x
            n=-n
        while n>0:
            if n%2==1:
                res=res*x
            x=x**2
            n//=2
        return res

面试题18 删除链表的节点

题目:

给定单向链表的头指针和一个要删除的节点的值,定义一个函数删除该节点。

返回删除后的链表的头节点。

解法:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode deleteNode(ListNode head, int val) {
        if(head.val==val) return head.next;
        ListNode pre=head;
        ListNode cur=head.next;
        while(cur!=null&&cur.val!=val){
            pre=cur;
            cur=cur.next;
        }
        if(cur!=null){
            pre.next=cur.next;
        }
        return head;

    }
}
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def deleteNode(self, head: ListNode, val: int) -> ListNode:
        if head.val==val: return head.next
        pre=head
        cur=head.next
        while cur and cur.val!=val:
            pre=cur
            cur=cur.next
        if cur:
            pre.next=cur.next
        return head
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值