Posts

Showing posts with the label Numbers

Search Insert Position

Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. You may assume no duplicates in the array. Example 1: Input: [1,3,5,6], 5 Output: 2 Example 2: Input: [1,3,5,6], 2 Output: 1 Example 3: Input: [1,3,5,6], 7 Output: 4 Example 4: Input: [1,3,5,6], 0 Output: 0   class Solution {     public int searchInsert(int[] nums, int target) {                 int i = 0, length = nums.length;                 for(i=0;i<length;i++){             if(nums[i] >= target){                 return i;             }   ...

Reverse Integer

Given a 32-bit signed integer, reverse digits of an integer. Example 1: Input: 123 Output: 321   Example 2: Input: -123 Output: -321   Example 3: Input: 120 Output: 21   Note: Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−2 31 ,  2 31  − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows. class Solution {     public int reverse(int x) {         StringBuilder sb;         String str = x+"";         int i;         if(x==0)             return 0;         if(x<0){             String sub1 = str.substring(0,1);  ...

Happy Number - LeetCode

A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers. Example:  Input: 19 Output: true Explanation: 1 2 + 9 2 = 82 8 2 + 2 2 = 68 6 2 + 8 2 = 100 1 2 + 0 2 + 0 2 = 1       Here the solution has to be done with in-build method. If we squaring the sum of each digit it will end up at 1, but in another case if sum is 4 it will be on loop and doesn't end. So we have to break the loop at 1 or 4. If 1 it is happy number else it is not a happy number. Click this link to try it on Leetcode class Solution {     public boolean isHappy(int n) {         int sum=0, t1;       ...