2 August 2019
Angular (48) -- Angular Service Worker
by Jerry Zhang
LeetCode Day 28: P190. Reverse Bits (Easy)
题目:
给一个32 bits的无符号整数,求它的二进制表示的反转数的十进制整数。
Input: 00000010100101000001111010011100
Output: 00111001011110000010100101000000
Explanation: The input binary string 00000010100101000001111010011100 represents the unsigned integer 43261596,
so return 964176192 which its binary representation is 00111001011110000010100101000000.
我的思路:
用Integer.toBinaryString
方法把n转换成二进制的字符串,然后反转,再转换回去。
坑:
写代码时发现需要先在前面补齐32位,并且最后必须用parseUnsignedInt
方法才对,因为要求是无符号的。
我的代码:
public class E_190_ReverseBits {
public static int reverseBits(int n) {
String s = Integer.toBinaryString(n);
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < 32 - s.length(); i++) {
stringBuilder.append(0);
}
stringBuilder.append(s);
char[] chars = new char[32];
stringBuilder.getChars(0, 32, chars, 0);
int l = 0;
int r = 31;
char temp;
while (l < r) {
temp = chars[l];
chars[l++] = chars[r];
chars[r--] = temp;
}
String s1 = new String(chars);
return Integer.parseUnsignedInt(s1, 2);
}
}
非常慢,只超过6%。
标准答案:
import java.lang.Math;
public class Solution {
// you need treat n as an unsigned value
public int reverseBits(int n) {
int[] digits = new int[32];
for(int i =0; i< 32;i++){
int tmp = n >> i & 1;
digits[i] = tmp;
}
int res = 0;
for(int i =0; i< 32; i++){
res += digits[i] << (31-i);
}
return res;
}
}
位运算。因为n内部本身就是用二进制表示的,所以想取得n的二进制表示的每个数字,只需要用for循环,每次把n向右平移i位,那跟1取“与”运算, 就能按顺序存到数组里了。
按倒序存到数组里后,每一个元素都是一个“0”或“1”的整数。再用一次for循环,把每个数字向左平移“31-i”位,加到结果的整数中。
Angular: Offline Application
What are Service Workers?
Service Workers can make our application run in an offline environment, means if we do not have network, the application can still run.
Typically, our JavaScript code runs in a single thread. We can run an additional thread called web worker.
Service Worker can listen to outgoing network requests and cache them.
Install Service Worker(pwa)
ng add @angular/pwa
In the app.module, we import a ServiceWorkerModule and the “ngsw-worker.js” file will be generated in the dist folder when the project is build.
ng build --prod
http-server@0.9
To test this, we can install a light-weight node server:
npm install -g http-server@0.9
Go into the folder:
cd dist/ng-pwa/
Run the server:
http-server -p 8081
Then, go to localhost:8081, the page is loaded. Press F12->Application->Service Worker.
If we check the offline
, and refresh the page, the requests are still sent, and we can see a white page instead of
the normal “no network” page.
If we have some static content in our page, it will be displayed.
Caching assets in ngsw-config.json
assetGroups is for the static files. dataGroups is for dynamic data.
"dataGroups": [
{
"name": "posts",
"urls": [
"https://jsonplaceholder.typicode.com/posts"
],
"cacheConfig": {
"maxSize": 5,
"maxAge": "6h",
"timeout": "10s",
"strategy": "freshness"
}
}
]