16.11.4
来源:互联网 发布:淘宝的评价管理在哪 编辑:程序博客网 时间:2024/06/03 11:12
189. Rotate Array
Rotate an array of n elements to the right by k steps.
For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4].
分析:将数组元素循环右移k个单位
public class Solution { public void rotate(int[] nums, int k) { /*I don't understand the role of k%=nums.length. Doesn't it change the value of k? I tried without it and i get index out of bound in the reverse function. This is because that sometimes, k is larger than the length of array. For example nums = [1, 2, 3, 4, 5], k = 12, this means we only need to rotate the last two numbers. k = k % nums.length = 2; */ //获取实际需要右移的位数 k%=nums.length; reverse(nums,0,nums.length-1); reverse(nums,0,k-1); reverse(nums,k,nums.length-1); } //逆序 public static void reverse(int[] nums,int start,int end){ int temp=0; for(int i=start,j=end;i<=j;i++,j--){ temp=nums[j]; nums[j]=nums[i]; nums[i]=temp; } }}
172. Factorial Trailing Zeroes
Given an integer n, return the number of trailing zeroes in n!.
分析:返回n!后面的尾0个数
public class Solution { public int trailingZeroes(int n) { int result=0; //将n除以5后的结果累加 while(n>0){ n/=5; result+=n; } return result; }}
190. Reverse Bits
Reverse bits of a given 32 bits unsigned integer.
For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represented in binary as 00111001011110000010100101000000).
分析:将32位无符号整数的二进制表示逆序(位操作)
public class Solution { // you need treat n as an unsigned value public int reverseBits(int n) { int result=0; for(int i=0;i<32;i++){ //先取出当前的最低位(n>>i&0x1),取出后右移舍弃一位 //将当前位左移到指定位置实现逆序 result|=(n>>i&0x1)<<(31-i); } return result; }}
191. Number of 1 Bits
Write a function that takes an unsigned integer and returns the number of ’1’ bits it has (also known as the Hamming weight).
For example, the 32-bit integer ’11’ has binary representation 00000000000000000000000000001011, so the function should return 3.
分析:将一个无符号整数用二进制表示,并且返回其中的位数为1的个数(位操作)
public class Solution { // you need to treat n as an unsigned value public int hammingWeight(int n) { int count=0; int temp=0; for(int i=0;i<32;i++){ //判断每一位是否为1 temp=(n>>i&0x1); if(temp==1)count++; } return count; }}
- 16.11.4
- 苏嵌4 16.11.2
- 苏嵌6 16.11.4
- 16.11.1
- 16.11.2
- 16.11.3
- 16.11.5
- 16.11.7
- 16.11.8
- 16.11.9
- 16.11.10
- 16.11.11
- 16.11.12
- 16.11.24
- 16.11.25
- 16.11.28
- 16.11.29
- 苏嵌3 16.11.1
- 【angularjs指令】简单的搜索框实现
- linux 时间函数
- redis通用key操作命令(总)
- 【品高云技巧】002.通过弹性IP控制网络流量(QoS)
- 数据库开源库使用基本方法总结
- 16.11.4
- Linux下chkconfig命令详解
- div+css简单实现圆形头像
- 1
- MODIFY TRANSPORTING
- setSpan时需要指定的flag参数含义
- 常用对象集合自定义排序
- 使用编辑器里的声音插件
- riot实现alert标签