想要我的财宝吗?想要的话可以全部给你,去找吧!我把所有反转都放在了那里!
(本文档仅涉及最基本的反转,如有需要比如从第几位到第几位进行反转的,抱歉,出门左拐>_<)
1.位反转
题目如图:
不多bb,直接上代码
方法一:(该方法适合任意个数bit的反转)
unsigned char bit_reverse(unsigned char c)
{
unsigned char buf = 0;
int bit = 8;
while(bit)
{
bit--;
buf |= ((c & 1) << bit);
c >>= 1;
}
return buf;
}
//源字符串右移,目标字符串左移
方法二:(该方法只适用于8bits,但是效率高,更快)
unsigned char bit_reverse(unsigned char c)
{
c = ((c & 0xaa) >> 1 | (c & 0x55) << 1);
c = ((c & 0xcc) >> 2 | (c & 0x33) << 2);
c = ((c & 0xf0) >> 4 | (c & 0x0f) << 4);
return c;
}
// 方法二主要思想:先每两位对调一下,再两位一组进行对调,最后四位一组进行对调,成功完成位反转
// 0xaa = 1010 1010; 0x55 = 0101 0101;
// 0xcc = 1100 1100; 0x33 = 0011 0011;
// 0xf0 = 1111 0000; 0x0f = 0000 1111;
// 缺点:该方法主要是针对特定位数,任意个数的bit序列使用方法一
第二个方法没懂?不用怕,下面一张图你就懂了
2.字符串反转
比如源字符串位“1234abcd”,则输出应为“dcba4321”
void str_reverse(char *p)
{
char temp, *s1,*s2;
s1 = p; //s1指向字符串第一个字符
s2 = s1 + strlen(p) - 1; //s2指向字符串最后一个字符(‘\0’除外)
while(s1<s2)
{ //就简单的交换呗
temp = *s1; //[1]
*s1 = *s2; //[2]
*s2 = temp; //[3]
s1++; //[4]
s2--; //[5]
}
}
emmm…也附上一张图吧
3.整数反转
题目:<来源:力扣>
给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转,
例如:
输入:321 输出:123
输入:-156 输出:-651
输入:210 输出:12
假设我们的环境只能存储得下 32 位的有符号整数,则其数值范围为 [−231, 231 − 1]。请根据这个假设,如果反转后整数溢出那么就返回 0。
int int_reverse(int x){
long y = 0;
while(x)
{
y = y*10 + x%10;
x = x/10;
}
return (y > -pow(2,31) && y < pow(2,31) - 1)?y:0;
}
关于这题不愿多说,放到这纯粹凑个数。不过注意y变量使用的long,防止溢出。
4.链表反转
题目:<来源:力扣>
反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
以下是C语言版本:
struct ListNode
{
int val; //存储数据
struct ListNode* next; //指向下一个节点的指针
};
struct ListNode* List_reverse(struct ListNode* head)
{
if(head == NULL || head->next == NULL)
return head; //如果可以,别落下这两句
struct ListNode* new_head, old_head, temp; //创建三个指针;
old_head = head; //将当前头指针赋给old_head
new = NULL; //初始化new_head指针指向NULL
while(old_head) //当old_head不为空时
{
temp = old_head->next;
old_head->next = new_head;
new_head = old_head;
old_head = temp;
}
head = new_head; //更新head
return head;
}
看到这不经吐槽一句,淦!最重要的循环里面不给注释!什么垃圾博主,毁我时间!
别着急,老样子,no pic you say j8,麻烦看到这的朋友点赞、收藏、分享好吧,画图真的很累的!!!
嗯,目前我想到的反转就这么多,欢迎留言补充,我会考虑加更…