Input: s ="1101"Output: 6Explanation: "1101" corressponds to number 13in their decimal representation.Step 1)13is odd, add 1 and obtain 14.Step 2)14is even, divide by 2 and obtain 7.Step 3)7is odd, add 1 and obtain 8.Step 4)8is even, divide by 2 and obtain 4.Step 5)4is even, divide by 2 and obtain 2.Step 6)2is even, divide by 2 and obtain 1.
Example 2:
1
2
3
4
Input: s ="10"Output: 1Explanation: "10" corressponds to number 2in their decimal representation.Step 1)2is even, divide by 2 and obtain 1.
classSolution {
publicintnumSteps(String s) {
int carry = 0;
int ans = 0;
for (int i = s.length() - 1; i >= 1; i--) {
int dig = s.charAt(i) -'0'+ carry;
// odd numberif (dig == 1) {
carry = 1;
ans += 2;
} elseif (dig == 0) {
carry = 0;
ans += 1;
} elseif (dig == 2) {
carry = 1;
ans += 1;
}
}
// last digit 1 needs to add a carried over digit 1, // which gives 10 in eg. 1// So need one more divide to make it 1, hence 1 more stepif (carry == 1) {
ans++;
}
return ans;
}
}
classSolution {
publicintnumSteps(String s) {
int carry = 0;
int ans = 0;
for (int i = s.length() - 1; i >= 1; i--) {
if (s.charAt(i) -'0'+ carry == 1) {
carry = 1;
ans += 2;
} else {
ans += 1;
}
}
// last digit 1 needs to add a carried over digit 1, // which gives 10 in eg. 1// So need one more divide to make it 1, hence 1 more stepif (carry == 1) {
ans++;
}
return ans + carry;
}
}
n =5carry =0s =1101index =0123---i =3=> s[i]=1carry + s[i]=1=> odd => carry =1, ans +=2=2---i =2=> s[i]=0, carry =1carry + s[i]=1=> odd => carry =1, ans +=2=4---i =1=> s[i]=1, carry =1carry + s[i]=2=> even => ans +=1=5---Finally, as carry =1, we increment ans +=1=6Return ans as 6